Detailed explanation of MySQ basic operation

Basic operation of MySQL

First of all, the keywords in the sql operation are case-insensitive, and create and CREATE are the same.

1. Library operation

1.1 Check the database

show databases;

insert image description here

  1. One or more spaces between show and databases
  2. Note that it is databases instead of database
  3. The semicolon at the end is the English form, and the semicolon in SQL means that a line is executed +
  4. For code, if there is no semicolon after the statement, then the default is to write a code in multiple lines (as shown in the figure below)

insert image description here

  1. The figure below is a feedback that will be obtained after each execution of a SQL statement. The feedback will tell us how many rows of records are in the current result and how much time it takes. In the figure below, set represents a collection, so it means that there are four rows in the current collection, and the execution takes a total of 0.01 seconds (sec = second seconds). Sometimes it will display 0.00 sec., which means less than 10 milliseconds, so it will not be displayed.

insert image description here

1.2 Create a database

CREATE DATABASE [IF NOT EXISTS] 数据库名称 [create_specification [, 
create_specification] ...]
create_specification:
 [DEFAULT] CHARACTER SET charset_name
 [DEFAULT] COLLATE collation_name

Uppercase indicates that the keyword
[] is optional
CHARACTER SET: specifies the character set used by the database
COLLATE: specifies the validation rules for the database character set

Grammar rules created

  1. The database name can be composed of numbers, letters, and underscores. The number cannot start with a number (same as a java variable name), and the name cannot be a sql keyword (such as show, database)

insert image description here

  1. If you just want to use keywords as the database name, you can use backticks ` to enclose the database name.
    insert image description hereThe error here is
    ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'databese' at line 1

Syntax means syntax, just understand it as grammar. manual——The manual
is more important to us than near 'databese' at line 1the sentence, the superficial error is near the database on the first line

  1. When creating a database, you can specify character sets and verification rules.
    When we create a database without specifying character sets and verification rules, the system uses the default character set: utf8, and the verification rules are: utf8_ general_ ci. Note
    : MySQL’s utf8 encoding is not real The utf8 does not contain some complex Chinese characters. The real utf8 of MySQL is to use utf8mb4, it is recommended that everyone use utf8mb4

example

1. Create a database named db_test1

CREATE DATABASE db_test1;

2. If the system does not have a database of db_test2, create a database named db_test2, if there is, do not create it

CREATE DATABASE IF NOT EXISTS db_test2;

3. If the system does not have a db_test database, create a db_test database that uses the utf8mb4 character set, and if so, do not create it

CREATE DATABASE IF NOT EXISTS db_test CHARACTER SET utf8mb4;

1.3 Using the database

use 数据库名;

example

insert image description here
After using the database, there will be a corresponding prompt, indicating that the database has been switched.

1.4 Delete the database

DROP DATABASE [IF EXISTS] db_name;

Deleting is very dangerous! Once deleted, the data is gone and difficult to recover.
After the database is deleted, the corresponding database cannot be seen internally, and all the tables and data in it are deleted

example

drop database if exists db_test1;
drop database if exists db_test2;

If there is a db_test1 table in the database, delete the database.

2. Table operation

When you need to operate the tables in the database, you need to use the database first

2.1 Create table

CREATETABLE table_name (
    field1 datatype,
    field2 datatype,
    field3 datatype
);

Example 1:

create table stu_test ( 
   id int,
   name varchar(20) comment '姓名',
   password varchar(50) comment '密码', 
   age int,
   sex varchar(1),
   birthday timestamp, 
   amout decimal(13,2), 
   resume text
);

insert image description here

  1. comment is equivalent to a comment, which is not very easy to use and can only be used when creating a table, so generally speaking, we recommend using # or – to indicate comments

insert image description here

2.2 View the table structure in the database

use 数据库名;
desc 表名;

Example:

desc stu_test;

insert image description here

  1. desc is an abbreviation for describe.
  2. There are often int(11) in the viewing results, which means that this column can display up to 11 characters when the short query is displayed. This is just display width, it has nothing to do with actual storage.
  3. The NULL column indicates whether it can be empty, if it is YES, it can be.
  4. Default represents the default value.

2.3 Delete the table structure in the database

use database_name;
drop table 表名;

2.4 Query all table names in a database

use database_name;
show tables;

3. Data types in SQL

3.1 Numerical types

insert image description here

  1. The numeric type can be specified as unsigned (unsigned), which means that negative numbers are not taken.
  2. For the range of integer types: signed range: -2 (number of bytes of type *8-1) to 2 (number of bytes of type *8-1) -1, if int is 4 bytes, it is -2 31 to 2 31-1; unsigned range: 0 to 2 (number of type bytes*8)-1, such as int is 2 32-1.
  3. When designing, try not to use unsigned. For data that may not fit in the int type, int unsigned may also not fit in the data. Instead of this, it is better to upgrade the int type to the bigint type when designing.
  4. BIT is often used to represent strings of binary numbers.
  5. DOUBLE(3,1) means three significant figures and one decimal place, so 10.2 is legal, but 10.20 is not legal.

Further clarification on DECIMA

FLOAT and DOUBLE have a very serious problem. When representing some data, they cannot be accurately represented (there is an error). We all know that FLOAT and DOUBLE represent data in the form of how many digits the base number and how many digits the exponent at the bottom layer. In this way The advantage is that the calculation speed is fast and the storage space is small, but there will be errors. So at this time, SQL provides DECIMAL (the English original meaning is decimal) to save accurate decimals, and its underlying storage method type and string.

3.2 String type

insert image description here

  1. VACHAR is a variable string, SIZE can specify the maximum length, and the unit is "character", so if VACHAR(10) represents a name, a name can store up to ten characters instead of five. At the same time, VACHAR(10) does not occupy the storage space of 10 characters at the beginning, which changes dynamically.
  2. BLOB stores binary strings. Note that it is different from BIT. BIT can store up to 64 binary numbers, and BLOB is longer. For example, if I want to save a smaller picture or audio file, I can use BLOB (about 64Kb).

3.3 date type

insert image description here

  1. TIMESTAMP is the timestamp

4. MySQL addition, deletion, modification and query

CRUD CRUD (Create (increase) Restrieve (check) Update (change) Delete (delete));

4.1 New Insert Data

First create a student table

mysql> create database base1  character set utf8mb4;;
Query OK, 1 row affected (0.00 sec)
mysql> use base1;
Database changed
mysql> DROP TABLE IF EXISTS student;
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> CREATE TABLE student (
    ->     id INT NOT NULL,
    ->     sn INT,
    ->     name VARCHAR(20),
    ->     qq_mail VARCHAR(20)
    -> );
mysql> desc student;
+---------+-------------+------+-----+---------+-------+
| Field   | Type        | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| id      | int(11)     | NO   |     | NULL    |       |
| sn      | int(11)     | YES  |     | NULL    |       |
| name    | varchar(20) | YES  |     | NULL    |       |
| qq_mail | varchar(20) | YES  |     | NULL    |       |
+---------+-------------+------+-----+---------+-------+
4 rows in set (0.00 sec)
Query OK, 0 rows affected (0.02 sec)

4.1.1 Basic insertion

insert [into] 表名 values [列名] (1,值2,值3.....);

example

mysql> insert into student values(123,4456,'张三','[email protected]');
Query OK, 1 row affected (0.00 sec)
mysql>  insert student (id,sn,name,qq_mail) values (123,4456,'张三','[email protected]');
Query OK, 1 row affected (0.00 sec)

Notice

  1. SQL does not have a character type, so '' "" all represent string types.
  2. If you encounter this kind of error Incorrect string value: '\xE5\xBC\xA0\xE4\xB8\x89' for column 'name' at row 1, it shows that the character value is incorrect, it may be a problem with the character set of the table, you need to delete the entire database, re-create the database and the table, and be sure to specify the character set as utf8mb4 when creating the database (utf8mb4 is more complete than utf8, and has more encodings for emoji expressions).
  3. Into in insert into can be omitted

4.1.2 Insertion of specified columns

insert [into] 表名 (列名1,列名2,列名3......) values(1,2,3,......)

Example:

mysql> insert student(id,qq_mail) values (213,'[email protected]');
Query OK, 1 row affected (0.00 sec)

Notice:

  1. It is defined in the previous table structure definition id INT NOT NULL,that the id cannot be empty, so the id cannot be created by default by the system

result

mysql> select * from student;
+-----+------+--------+---------------+
| id  | sn   | name   | qq_mail       |
+-----+------+--------+---------------+
| 123 | 4456 | 张三   | 123456@qq.com |
| 123 | 4456 | 张三   | 123456@qq.com |
| 213 | NULL | NULL   | 34567@qq.com  |
+-----+------+--------+---------------+
3 rows in set (0.00 sec)

4.1.3 Multiple data insertion

Example:

mysql> insert into student values(1,1,"李四","[email protected]"),(2,2,"李四","[email protected]");

result

mysql> select * from student;
+-----+------+--------+---------------+
| id  | sn   | name   | qq_mail       |
+-----+------+--------+---------------+
| 123 | 4456 | 张三   | 123456@qq.com |
| 123 | 4456 | 张三   | 123456@qq.com |
| 213 | NULL | NULL   | 34567@qq.com  |
|   1 |    1 | 李四   | 1@qq.com      |
|   2 |    2 | 李四   | 2@qq.com      |
+-----+------+--------+---------------+
5 rows in set (0.00 sec)
  1. Inserting N records at a time is more efficient than inserting one record at a time and inserting N times, because MySQL is in c/s mode, and each request requires an interaction between the client and the server. The former interacted once, and the latter interacted multiple times.

4.1.4 Insertion of time and date types

The insertion time is to express the time and date through a specific time and date.
It is in the form of
'2023-02-17 21:25:20'

example

mysql> create table homework(id int,createTime datetime);
Query OK, 0 rows affected (0.03 sec)
mysql> insert into homework values(1,'2023-12-25 18:32:16');
Query OK, 1 row affected (0.00 sec)
mysql> select * from homework;
+------+---------------------+
| id   | createTime          |
+------+---------------------+
|    1 | 2023-12-25 18:32:16 |
+------+---------------------+
1 row in set (0.00 sec)

At the same time, SQL also provides the now() function to return the current time.
Example:

mysql> insert into homework values(2,now());
Query OK, 1 row affected (0.00 sec)

mysql> select * from homework;
+------+---------------------+
| id   | createTime          |
+------+---------------------+
|    1 | 2023-12-25 18:32:16 |
|    2 | 2023-06-02 12:04:26 |
+------+---------------------+
2 rows in set (0.00 sec)

4.2 query data SELECT

4.2.1 Full Column Search

select * from 表名

It is very dangerous to execute select * in actual operation, because the amount of data in the actual project is very large. If all the data is read from the server to the client, the data bandwidth will be congested.

4.2.2 Specify column lookup

select 列名,列名 from 表名;

Example:

mysql> select id,name from student;
+-----+--------+
| id  | name   |
+-----+--------+
| 123 | 张三   |
| 123 | 张三   |
| 213 | NULL   |
|   1 | 李四   |
|   2 | 李四   |
+-----+--------+
5 rows in set (0.00 sec)

4.2.3 Queries can be expressions

Example:

Let's first create a test score table

mysql> DROP TABLE IF EXISTS exam_result;
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> CREATE TABLE exam_result (
    ->     id INT,
    ->     name VARCHAR(20),
    ->     chinese DECIMAL(3,1),
    ->     math DECIMAL(3,1),
    ->     english DECIMAL(3,1)
    -> );
Query OK, 0 rows affected (0.03 sec)

mysql> -- 插入测试数据
mysql> INSERT INTO exam_result (id,name, chinese, math, english) VALUES
    ->     (1,'唐三藏', 67, 98, 56),
    ->     (2,'孙悟空', 87.5, 78, 77),
    ->     (3,'猪悟能', 88, 98.5, 90),
    ->     (4,'曹孟德', 82, 84, 67),
    ->     (5,'刘玄德', 55.5, 85, 45),
    ->     (6,'孙权', 70, 73, 78.5),
    ->     (7,'宋公明', 75, 65, 30);
Query OK, 7 rows affected (0.01 sec)
Records: 7  Duplicates: 0  Warnings: 0

mysql> select * from exam_result;
+------+-----------+---------+------+---------+
| id   | name      | chinese | math | english |
+------+-----------+---------+------+---------+
|    1 | 唐三藏    |    67.0 | 98.0 |    56.0 |
|    2 | 孙悟空    |    87.5 | 78.0 |    77.0 |
|    3 | 猪悟能    |    88.0 | 98.5 |    90.0 |
|    4 | 曹孟德    |    82.0 | 84.0 |    67.0 |
|    5 | 刘玄德    |    55.5 | 85.0 |    45.0 |
|    6 | 孙权      |    70.0 | 73.0 |    78.5 |
|    7 | 宋公明    |    75.0 | 65.0 |    30.0 |
+------+-----------+---------+------+---------+
7 rows in set (0.00 sec)

We can query the results after everyone's math score +10

mysql> -- 查询所有人的数学成绩+10分的结果
mysql> select math+10 from exam_result;
+---------+
| math+10 |
+---------+
|   108.0 |
|    88.0 |
|   108.5 |
|    94.0 |
|    95.0 |
|    83.0 |
|    75.0 |
+---------+
7 rows in set (0.00 sec)

But note: After the above query, the data in the hard disk of the database server has not changed. Because mysql is a C/S mode, the sql entered by the user on the client is sent to the server through a request, the server parses and executes the sql, reads the query result from the hard disk, and returns it to the client through the network response. The data is displayed in the form of a temporary table .
In fact, careful students can find that the actual definition exam_resultis math DECIMAL(3,1),that the data in the column of math should be three significant figures, and one decimal place, but math+10 is not difficult to find, the first line here is 108.0 because of the The table is a temporary table .

You can also put multiple columns together to calculate
, such as querying the average grade of each student

mysql> select name,(math+chinese+english)/3 from exam_result;
+-----------+--------------------------+
| name      | (math+chinese+english)/3 |
+-----------+--------------------------+
| 唐三藏    |                 73.66667 |
| 孙悟空    |                 80.83333 |
| 猪悟能    |                 92.16667 |
| 曹孟德    |                 77.66667 |
| 刘玄德    |                 61.83333 |
| 孙权      |                 73.83333 |
| 宋公明    |                 56.66667 |
+-----------+--------------------------+
7 rows in set (0.00 sec)

4.2.4 Specify an alias

Specify an alias for the column in the query result, indicating that the returned result set uses the alias as the name of the column

SELECT 表达式 [AS] 别名 [...] FROM table_name;

Example:

mysql> SELECT id, name, (chinese + math + english)/3  as 平均分 FROM exam_result;
+------+-----------+-----------+
| id   | name      | 平均分    |
+------+-----------+-----------+
|    1 | 唐三藏    |  73.66667 |
|    2 | 孙悟空    |  80.83333 |
|    3 | 猪悟能    |  92.16667 |
|    4 | 曹孟德    |  77.66667 |
|    5 | 刘玄德    |  61.83333 |
|    6 | 孙权      |  73.83333 |
|    7 | 宋公明    |  56.66667 |
+------+-----------+-----------+
7 rows in set (0.00 sec)

4.3 Deduplication DISTINCT

mysql> select  distinct math from exam_result;
+------+
| math |
+------+
| 98.0 |
| 78.0 |
| 98.5 |
| 84.0 |
| 85.0 |
| 73.0 |
| 65.0 |
+------+
7 rows in set (0.00 sec)

distinct can also deduplicate multiple columns, but only if the element values ​​of each column are the same, it will be removed. If there is a column that is different, SQL thinks that it cannot be deduplicated.
Also, the following way of writing is wrong

mysql> select name,(distinct mat)h from exam_result; -- 错误
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'distinct mat)h from exam_result' at line 1
mysql> select name, distinct math from exam_result; -- 错误
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'distinct math from exam_result' at line 1

4.4 Query result sorting ORDER BY

4.4.1 order by child clause

grammar:

-- ASC 为升序(从小到大)
-- DESC 为降序(从大到小)
-- 默认为 ASC
SELECT ... FROM table_name [WHERE ...] 
 ORDER BY column [ASC|DESC], [...];

Example:

mysql> select * from exam_result order by math asc;
+------+-----------+---------+------+---------+
| id   | name      | chinese | math | english |
+------+-----------+---------+------+---------+
|    7 | 宋公明    |    75.0 | 65.0 |    30.0 |
|    6 | 孙权      |    70.0 | 73.0 |    78.5 |
|    2 | 孙悟空    |    87.5 | 78.0 |    77.0 |
|    4 | 曹孟德    |    82.0 | 84.0 |    67.0 |
|    5 | 刘玄德    |    55.5 | 85.0 |    45.0 |
|    1 | 唐三藏    |    67.0 | 98.0 |    56.0 |
|    3 | 猪悟能    |    88.0 | 98.5 |    90.0 |
+------+-----------+---------+------+---------+
7 rows in set (0.00 sec)

Notice:

  1. For mySql, when we do not specify the order by (query order), the order of the query data displayed at this time is unpredictable, and the logic of the code cannot depend on this.
  2. NULL data sorting, as smaller than any value, ascending order appears at the top, descending order appears at the bottom.

4.4.2 Sorting using expressions and aliases

mysql> select *,(math+chinese+english) as 总分 from exam_result order by math desc;
+------+-----------+---------+------+---------+--------+
| id   | name      | chinese | math | english | 总分   |
+------+-----------+---------+------+---------+--------+
|    3 | 猪悟能    |    88.0 | 98.5 |    90.0 |  276.5 |
|    1 | 唐三藏    |    67.0 | 98.0 |    56.0 |  221.0 |
|    5 | 刘玄德    |    55.5 | 85.0 |    45.0 |  185.5 |
|    4 | 曹孟德    |    82.0 | 84.0 |    67.0 |  233.0 |
|    2 | 孙悟空    |    87.5 | 78.0 |    77.0 |  242.5 |
|    6 | 孙权      |    70.0 | 73.0 |    78.5 |  221.5 |
|    7 | 宋公明    |    75.0 | 65.0 |    30.0 |  170.0 |
+------+-----------+---------+------+---------+--------+
7 rows in set (0.00 sec)

mysql> select *,(math+chinese+english) as 总分 from exam_result order by 总分 desc;
+------+-----------+---------+------+---------+--------+
| id   | name      | chinese | math | english | 总分   |
+------+-----------+---------+------+---------+--------+
|    3 | 猪悟能    |    88.0 | 98.5 |    90.0 |  276.5 |
|    2 | 孙悟空    |    87.5 | 78.0 |    77.0 |  242.5 |
|    4 | 曹孟德    |    82.0 | 84.0 |    67.0 |  233.0 |
|    6 | 孙权      |    70.0 | 73.0 |    78.5 |  221.5 |
|    1 | 唐三藏    |    67.0 | 98.0 |    56.0 |  221.0 |
|    5 | 刘玄德    |    55.5 | 85.0 |    45.0 |  185.5 |
|    7 | 宋公明    |    75.0 | 65.0 |    30.0 |  170.0 |
+------+-----------+---------+------+---------+--------+
7 rows in set (0.00 sec)

4.4.3 Multiple fields can be sorted, and the sorting priority follows the writing order

Example:

mysql> select * from exam_result order by math asc,chinese desc,english asc;
+------+-----------+---------+------+---------+
| id   | name      | chinese | math | english |
+------+-----------+---------+------+---------+
|    7 | 宋公明    |    75.0 | 65.0 |    30.0 |
|    6 | 孙权      |    70.0 | 73.0 |    78.5 |
|    2 | 孙悟空    |    87.5 | 78.0 |    77.0 |
|    4 | 曹孟德    |    82.0 | 84.0 |    67.0 |
|    5 | 刘玄德    |    55.5 | 85.0 |    45.0 |
|    1 | 唐三藏    |    67.0 | 98.0 |    56.0 |
|    3 | 猪悟能    |    88.0 | 98.5 |    90.0 |
+------+-----------+---------+------+---------+
7 rows in set (0.00 sec)

4.5 Condition query WHERE

Comparison Operators
insert image description here
Logical Operators
insert image description here

Notice:

  1. WHERE conditions can use expressions, but not aliases.
  2. The priority of AND is higher than that of OR. When using it at the same time, you need to use parentheses () to wrap the priority execution part

4.5.1 Comparison operation

Example:

  1. Query the information of students whose English scores are less than 60
mysql> select * from exam_result where english < 60;
+------+-----------+---------+------+---------+
| id   | name      | chinese | math | english |
+------+-----------+---------+------+---------+
|    1 | 唐三藏    |    67.0 | 98.0 |    56.0 |
|    5 | 刘玄德    |    55.5 | 85.0 |    45.0 |
|    7 | 宋公明    |    75.0 | 65.0 |    30.0 |
+------+-----------+---------+------+---------+
3 rows in set (0.00 sec)

Note: The bottom layer of this line of code is like this. For the table of the database, traverse the table, take out the data of each row, and bring the data into the condition to see if the condition is met. If it is true, keep it. If it is false, it will not reserve.

  1. Query students whose Chinese scores are better than English scores
mysql> select name,english,chinese from exam_result where english < chinese;
+-----------+---------+---------+
| name      | english | chinese |
+-----------+---------+---------+
| 唐三藏    |    56.0 |    67.0 |
| 孙悟空    |    77.0 |    87.5 |
| 曹孟德    |    67.0 |    82.0 |
| 刘玄德    |    45.0 |    55.5 |
| 宋公明    |    30.0 |    75.0 |
+-----------+---------+---------+
5 rows in set (0.00 sec)
  1. Query students whose total score is below 200
mysql> select * from exam_result where english+chinese+math > 200;
+------+-----------+---------+------+---------+
| id   | name      | chinese | math | english |
+------+-----------+---------+------+---------+
|    1 | 唐三藏    |    67.0 | 98.0 |    56.0 |
|    2 | 孙悟空    |    87.5 | 78.0 |    77.0 |
|    3 | 猪悟能    |    88.0 | 98.5 |    90.0 |
|    4 | 曹孟德    |    82.0 | 84.0 |    67.0 |
|    6 | 孙权      |    70.0 | 73.0 |    78.5 |
+------+-----------+---------+------+---------+
5 rows in set (0.00 sec)

Note
look at the code below

mysql> select name,chinese+math+english as 总分 from exam_result where 总分 > 200;
ERROR 1054 (42S22): Unknown column '总分' in 'where clause'

Aliases cannot be used as where conditions. This is related to the execution order of SQL, and it is also stipulated by SQL syntax. The execution process of the above code is:
1. Traverse each row;
2. Bring this row into the condition of where;
3. For the result that meets the condition, query and calculate according to the column specified here in select.

But the order by keyword is ok

mysql> select name,chinese+math+english as 总分 from exam_result order by 总分 ;
+-----------+--------+
| name      | 总分   |
+-----------+--------+
| 宋公明    |  170.0 |
| 刘玄德    |  185.5 |
| 唐三藏    |  221.0 |
| 孙权      |  221.5 |
| 曹孟德    |  233.0 |
| 孙悟空    |  242.5 |
| 猪悟能    |  276.5 |
+-----------+--------+
7 rows in set (0.00 sec)

4.5.2 Logical operations

Example:

mysql> -- 查询语文成绩大于80分,且英语成绩大于80分的同学
mysql> SELECT * FROM exam_result WHERE chinese > 80 and english > 80;
+------+-----------+---------+------+---------+
| id   | name      | chinese | math | english |
+------+-----------+---------+------+---------+
|    3 | 猪悟能    |    88.0 | 98.5 |    90.0 |
+------+-----------+---------+------+---------+
1 row in set (0.00 sec)

mysql> -- 查询语文成绩大于80分,或英语成绩大于80分的同学
mysql> SELECT * FROM exam_result WHERE chinese > 80 or english > 80;
+------+-----------+---------+------+---------+
| id   | name      | chinese | math | english |
+------+-----------+---------+------+---------+
|    2 | 孙悟空    |    87.5 | 78.0 |    77.0 |
|    3 | 猪悟能    |    88.0 | 98.5 |    90.0 |
|    4 | 曹孟德    |    82.0 | 84.0 |    67.0 |
+------+-----------+---------+------+---------+
3 rows in set (0.00 sec)
mysql> -- 观察AND 和 OR 的优先级:
mysql> SELECT * FROM exam_result WHERE chinese > 80 or math>70 and english > 70;
+------+-----------+---------+------+---------+
| id   | name      | chinese | math | english |
+------+-----------+---------+------+---------+
|    2 | 孙悟空    |    87.5 | 78.0 |    77.0 |
|    3 | 猪悟能    |    88.0 | 98.5 |    90.0 |
|    4 | 曹孟德    |    82.0 | 84.0 |    67.0 |
|    6 | 孙权      |    70.0 | 73.0 |    78.5 |
+------+-----------+---------+------+---------+
4 rows in set (0.00 sec)

mysql> SELECT * FROM exam_result WHERE (chinese > 80 or math>70) and english > 70;
+------+-----------+---------+------+---------+
| id   | name      | chinese | math | english |
+------+-----------+---------+------+---------+
|    2 | 孙悟空    |    87.5 | 78.0 |    77.0 |
|    3 | 猪悟能    |    88.0 | 98.5 |    90.0 |
|    6 | 孙权      |    70.0 | 73.0 |    78.5 |
+------+-----------+---------+------+---------+
3 rows in set (0.00 sec)

The priority of AND is higher than that of OR, and when used at the same time, parentheses () need to be used to wrap the priority execution part.

4.5.3between and

Example:

mysql> -- 查询语文成绩在 [80, 90] 分的同学及语文成绩
mysql> SELECT name, chinese FROM exam_result WHERE chinese BETWEEN 80 AND 90;
+-----------+---------+
| name      | chinese |
+-----------+---------+
| 孙悟空    |    87.5 |
| 猪悟能    |    88.0 |
| 曹孟德    |    82.0 |
+-----------+---------+
3 rows in set (0.00 sec)

mysql> -- 使用 AND 也可以实现
mysql> SELECT name, chinese FROM exam_result WHERE chinese >= 80 AND chinese
    -> <= 90;
+-----------+---------+
| name      | chinese |
+-----------+---------+
| 孙悟空    |    87.5 |
| 猪悟能    |    88.0 |
| 曹孟德    |    82.0 |
+-----------+---------+
3 rows in set (0.00 sec)

4.5.4 in

Example:

mysql> -- 查询数学成绩是 58 或者 59 或者 98 或者 99 分的同学及数学成绩
mysql> SELECT name, math FROM exam_result WHERE math IN (58, 59, 98, 99);
+-----------+------+
| name      | math |
+-----------+------+
| 唐三藏    | 98.0 |
+-----------+------+
1 row in set (0.00 sec)

mysql> -- 使用 OR 也可以实现
mysql> SELECT name, math FROM exam_result WHERE math = 58 OR math = 59 OR math
    -> = 98 OR math = 99;
+-----------+------+
| name      | math |
+-----------+------+
| 唐三藏    | 98.0 |
+-----------+------+
1 row in set (0.00 sec)

4.5.5 Fuzzy query: LIKE

Like only supports two usages compared to regular expressions

  1. Use % to represent any N characters (including 0 characters);
  2. Use _ to represent any character.

Example:

mysql> select * from exam_result where name like '孙%';
+------+-----------+---------+------+---------+
| id   | name      | chinese | math | english |
+------+-----------+---------+------+---------+
|    2 | 孙悟空    |    87.5 | 78.0 |    77.0 |
|    6 | 孙权      |    70.0 | 73.0 |    78.5 |
+------+-----------+---------+------+---------+
2 rows in set (0.00 sec)
mysql> select * from exam_result where name like '孙_';
+------+--------+---------+------+---------+
| id   | name   | chinese | math | english |
+------+--------+---------+------+---------+
|    6 | 孙权   |    70.0 | 73.0 |    78.5 |
+------+--------+---------+------+---------+
1 row in set (0.00 sec)

4.5.6 NULL query: IS [NOT] NULL

When using null as a query condition, that is, to delete data that is empty in a certain column, you can use is null and < = > null, such statements, but at this time, pay attention to the difference between = null and < = >

Example:

mysql> select * from exam_result;
+------+--------+---------+------+---------+
| id   | name   | chinese | math | english |
+------+--------+---------+------+---------+
|    1 | 唐三藏 |    67.0 | 98.0 |    56.0 |
|    2 | 孙悟空 |    87.5 | 78.0 |    77.0 |
|    3 | 猪悟能 |    88.0 | 98.5 |    90.0 |
|    4 | 曹孟德 |    82.0 | 84.0 |    67.0 |
|    5 | 刘玄德 |    55.5 | 85.0 |    45.0 |
|    6 | 孙权   |    70.0 | 73.0 |    78.5 |
|    7 | 宋公明 |    75.0 | 65.0 |    30.0 |
|    1 | 贾宝玉 |    NULL | NULL |    NULL |
+------+--------+---------+------+---------+
8 rows in set (0.00 sec)

mysql> select * from exam_result where chinese = null;
Empty set (0.00 sec)
mysql> select * from exam_result where chinese <=> null;
+------+--------+---------+------+---------+
| id   | name   | chinese | math | english |
+------+--------+---------+------+---------+
|    1 | 贾宝玉 |    NULL | NULL |    NULL |
+------+--------+---------+------+---------+
1 row in set (0.00 sec)

mysql> select * from exam_result where chinese is not null;
+------+--------+---------+------+---------+
| id   | name   | chinese | math | english |
+------+--------+---------+------+---------+
|    1 | 唐三藏 |    67.0 | 98.0 |    56.0 |
|    2 | 孙悟空 |    87.5 | 78.0 |    77.0 |
|    3 | 猪悟能 |    88.0 | 98.5 |    90.0 |
|    4 | 曹孟德 |    82.0 | 84.0 |    67.0 |
|    5 | 刘玄德 |    55.5 | 85.0 |    45.0 |
|    6 | 孙权   |    70.0 | 73.0 |    78.5 |
|    7 | 宋公明 |    75.0 | 65.0 |    30.0 |
+------+--------+---------+------+---------+
7 rows in set (0.00 sec)

Note that
select * from exam_result where Chinese = nullafter the execution, it will not return the rows whose Chinese column is equal to null, because Chinese = null will return null or false after successful execution. That is, the default query condition is not established, so it will not be filtered at all.

4.5 Pagination query LIMIT

grammar:

-- 起始下标为 0
-- 从 0 开始,筛选 n 条结果
SELECT ... FROM table_name [WHERE ...] [ORDER BY ...] LIMIT n;
-- 从 s 开始,筛选 n 条结果
SELECT ... FROM table_name [WHERE ...] [ORDER BY ...] LIMIT s, n;
-- 从 s 开始,筛选 n 条结果,比第二种用法更明确,建议使用
SELECT ... FROM table_name [WHERE ...] [ORDER BY ...] LIMIT n OFFSET s;

Example:

mysql> select * from exam_result limit 3;
+------+--------+---------+------+---------+
| id   | name   | chinese | math | english |
+------+--------+---------+------+---------+
|    1 | 唐三藏 |    67.0 | 98.0 |    56.0 |
|    2 | 孙悟空 |    87.5 | 78.0 |    77.0 |
|    3 | 猪悟能 |    88.0 | 98.5 |    90.0 |
+------+--------+---------+------+---------+
3 rows in set (0.00 sec)

mysql> select * from exam_result limit 3 offset 2;
+------+--------+---------+------+---------+
| id   | name   | chinese | math | english |
+------+--------+---------+------+---------+
|    3 | 猪悟能 |    88.0 | 98.5 |    90.0 |
|    4 | 曹孟德 |    82.0 | 84.0 |    67.0 |
|    5 | 刘玄德 |    55.5 | 85.0 |    45.0 |
+------+--------+---------+------+---------+
3 rows in set (0.00 sec)

mysql> select * from exam_result limit 3,2;
+------+--------+---------+------+---------+
| id   | name   | chinese | math | english |
+------+--------+---------+------+---------+
|    4 | 曹孟德 |    82.0 | 84.0 |    67.0 |
|    5 | 刘玄德 |    55.5 | 85.0 |    45.0 |
+------+--------+---------+------+---------+
2 rows in set (0.00 sec)

Note: The order of sn limit s,nhere limit n offset sis reversed. s indicates where to start displaying, and n indicates how many lines to display.

The limit statement is often used together with other query conditional statements to achieve a combined effect

Example
To find the top three students with a total score

mysql> select id,name,chinese+math+english as 总分 from exam_result order by 总分 desc limit 3;
+------+--------+-------+
| id   | name   | 总分  |
+------+--------+-------+
|    3 | 猪悟能 | 276.5 |
|    2 | 孙悟空 | 242.5 |
|    4 | 曹孟德 | 233.0 |
+------+--------+-------+
3 rows in set (0.00 sec)

4.6 Modify the statement UPDATE

grammar:

UPDATE table_name SET 列名1 = 数值1 [, 列名2 = 数值2 ...]
 [WHERE ...] [ORDER BY ...] [LIMIT ...]

Example:

mysql> -- 将孙悟空的数学成绩变更为80分
mysql> update exam_result set math = 10 where name = "孙悟空";
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> -- 将曹孟德同学的数学成绩变更为 60 分,语文成绩变更为 70 分
mysql> update exam_result set math = 60,chinese = 70 where name = "曹孟德";
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> -- 将总成绩倒数前三的 3 位同学的数学成绩加上 30 分
mysql> update exam_result set math = math+30 order by math+chinese+english limit 3;
Query OK, 2 rows affected (0.01 sec)
Rows matched: 3  Changed: 2  Warnings: 0

Here are a few points to note,

  1. When null and numerical calculations, the return value is still null. For example, in this case, add 30 points to the math scores of the three students with the bottom three in the total score. The bottom one in the total score is Jia Baoyu math Chinese English All are null, after executing this sentence, it will not all become 30, but still be null, because null +10 = null.
  2. If update changes the data beyond the range of the existing type, it will directly report an error and will not change
  3. math = math +10; does not support abbreviation as mate+= 10 in SQL;

4.7 delete DELETE

grammar

DELETEFROM  table_name [WHERE ...] [ORDERBY ...] [LIMIT ...]

example

mysql> -- 删除孙悟空同学的考试成绩
mysql> delete from exam_result where name = "孙悟空";
Query OK, 1 row affected (0.01 sec)

mysql> -- 删除姓孙的同学的考试成绩
mysql> delete from exam_result where name like "孙%";
Query OK, 1 row affected (0.01 sec)

mysql> -- 删除数学第一名的同学的考试成绩
mysql>- delete from exam_result order by math desc limit 1;

mysql> -- 删除整张exam_result表
mysql> delete from exam_result ;

Note
delete from 表名that drop 表名the former means that the content in the table is deleted, but the table is still there, while the latter means that the entire table is directly deleted.

5. Database Constraints

5.1 Constraint types

  1. NOT NULL - Indicates that a column cannot store NULL values.
  2. UNIQUE - Guarantees that each row of a column must have a unique value.
  3. DEFAULT - specifies the default value when no value is assigned to the column.
  4. PRIMARY KEY - A combination of NOT NULL and UNIQUE . Ensuring that a column (or a combination of two or more columns) is uniquely identified makes it easier and faster to find a particular record in a table.
  5. FOREIGN KEY - Guarantees referential integrity where data in one table matches values ​​in another table.
  6. CHECK - Guarantees that the values ​​in the column meet the specified criteria. For MySQL databases, the CHECK clause is parsed, but the CHECK clause is ignored.

5.2 NULL constraints and NOT NULL constraints

When creating a table, you can specify that a column is not empty:
Example

mysql> create table student (id int not null,name varchar(20),qq_email varchar(10));
Query OK, 0 rows affected (0.03 sec)
mysql> desc student;
+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| id       | int(11)     | NO   |     | NULL    |       |
| name     | varchar(20) | YES  |     | NULL    |       |
| qq_email | varchar(10) | YES  |     | NULL    |       |
+----------+-------------+------+-----+---------+-------+
3 rows in set (0.01 sec)

After setting the constraint NOT NULL for this column, an error will be reported once this row is inserted with id = null.

5.3UNIQUE: unique constraint

When inserting or modifying data, it will first query to see if the data already exists. If it does not exist, it can be inserted and modified successfully. If it exists, the insertion or modification will fail.

Example:

mysql> create table student (id int unique,name varchar(10) not null);
Query OK, 0 rows affected (0.02 sec)

mysql> desc student;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(11)     | YES  | UNI | NULL    |       |
| name  | varchar(10) | NO   |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql> insert into student values(1,"zhangsan");
Query OK, 1 row affected (0.00 sec)

mysql> select * from student;
+------+----------+
| id   | name     |
+------+----------+
|    1 | zhangsan |
+------+----------+
1 row in set (0.00 sec)

mysql> insert into student values(1,"lisi");
ERROR 1062 (23000): Duplicate entry '1' for key 'id'

duplicate duplicate, entry entry, entry

5.4 DEFAULT: Default Value Constraints

  1. The default value is that when the specified column of insert is inserted, other unspecified columns are filled according to the default value.
  2. When we build a table, if we do not specify a default value, then SQL will automatically set the default value to null.

Example:
When specifying to insert data, the name column is empty, and the default value is "Anonymous"

mysql> drop table if exists student;
Query OK, 0 rows affected (0.01 sec)

mysql> create table student(id int unique,name varchar(20) default "无名氏");
Query OK, 0 rows affected (0.02 sec)

mysql> insert into student(id) values(1);
Query OK, 1 row affected (0.00 sec)

mysql> select * from student;
+------+--------+
| id   | name   |
+------+--------+
|    1 | 无名氏 |
+------+--------+
1 row in set (0.00 sec)

5.5 PRIMARY KEY: primary key constraint

  1. The primary key is the identity of a record in the table, uniquely marking each piece of data
  2. mySQL requires that the column (attribute) identified by the primary key is unique (unique) and cannot be empty (not null)
  3. There can only be one primary key in a table
  4. When creating a primary key, you can use one column as the primary key, but you can also use two or more columns as the primary key (composite primary key). But in general projects, a column is used as the primary key in a table.
mysql> drop table if exists student;
Query OK, 0 rows affected (0.01 sec)

mysql> create table student (id int primary key,name varchar(20) not null);
Query OK, 0 rows affected (0.02 sec)

mysql> desc student;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(11)     | NO   | PRI | NULL    |       |
| name  | varchar(20) | NO   |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
  1. For the primary key of integer type, it is often used with auto_increment. When the corresponding field of the inserted data does not give a value, the maximum value +1 is used. That is to say, mySQl itself will maintain a self-incrementing primary key similar to a global variable. After we set the attribute as an integer type primary key, the attribute insertion can be unassigned (that is, it can be null). At this time, MySQL will use the current primary key Add 1 to the maximum value to assign the primary key value of the current row.
  2. Auto-increment primary keys are generally only applicable to data deployed on a single machine. At this time, auto-increment primary keys are generally sufficient, but if auto-increment primary keys are deployed in a distributed manner, auto-increment primary keys are generally not applicable.

example

mysql> drop table if exists student;
Query OK, 0 rows affected (0.01 sec)
ysql> create table student (id int primary key auto_increment,name varchar(20));
Query OK, 0 rows affected (0.02 sec)

mysql> desc student;
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(11)     | NO   | PRI | NULL    | auto_increment |
| name  | varchar(20) | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

mysql> insert into student(name) values("张三");
Query OK, 1 row affected (0.00 sec)

mysql> select * from student;
+----+------+
| id | name |
+----+------+
|  1 | 张三 |
+----+------+
1 row in set (0.00 sec)
mysql> insert into student(id,name) values(null,"李四");
Query OK, 1 row affected (0.00 sec)

mysql> select * from student;
+----+------+
| id | name |
+----+------+
|  1 | 张三 |
|  2 | 李四 |
+----+------+
2 rows in set (0.00 sec)

mysql> insert into student values(100,"王五");
Query OK, 1 row affected (0.00 sec)

mysql> select * from student;
+-----+------+
| id  | name |
+-----+------+
|   1 | 张三 |
|   2 | 李四 |
| 100 | 王五 |
+-----+------+
3 rows in set (0.00 sec)

mysql> select * from student;
+-----+------+
| id  | name |
+-----+------+
|   1 | 张三 |
|   2 | 李四 |
| 100 | 王五 |
| 101 | 六六 |
+-----+------+
4 rows in set (0.00 sec)

5.6 FOREIGN KEY: foreign key constraints

grammar:

foreign key (字段名) references 主表()

example

mysql> create table class (classId int primary key auto_increment ,className varchar(20));
Query OK, 0 rows affected (0.02 sec)

mysql> drop table if exists student;
Query OK, 0 rows affected (0.01 sec)

mysql> create table student(studentId int primary key ,studentName varchar(20),classId int,
    -> foreign key (classId) references class(classId));
Query OK, 0 rows affected (0.02 sec)

mysql> desc student;
+-------------+-------------+------+-----+---------+-------+
| Field       | Type        | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| studentId   | int(11)     | NO   | PRI | NULL    |       |
| studentName | varchar(20) | YES  |     | NULL    |       |
| classId     | int(11)     | YES  | MUL | NULL    |       |
+-------------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> desc class;
+-----------+-------------+------+-----+---------+----------------+
| Field     | Type        | Null | Key | Default | Extra          |
+-----------+-------------+------+-----+---------+----------------+
| classId   | int(11)     | NO   | PRI | NULL    | auto_increment |
| className | varchar(20) | YES  |     | NULL    |                |
+-----------+-------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

  1. At this time, the class table is empty. If I add a new record in the student table (the classId in this record is 1), then an error will be reported.
    Example:
mysql> insert into student values(123,"zhangsan",1);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`base1`.`student`, CONSTRAINT `student_ibfk_1` FOREIGN KEY (`classId`) REFERENCES `class` (`classId`))

Among them, Cannot add or update a child row: a foreign key constraint fails (base1 .student , CONSTRAINT student_ibfk_1 FOREIGN KEY (classId ) REFERENCES class (classId ))
The classId in the student is constrained by the classId in the class table. In MySQL, we call the student table the child table, and the class table the parent table. This sentence translates "cannot add or modify a child row: a foreign key constraint (constraint) failed"

mysql> insert into class values(null,"一班"),(null,"二班");
Query OK, 2 rows affected (0.00 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> select * from class;
+---------+-----------+
| classId | className |
+---------+-----------+
|       1 | 一班      |
|       2 | 二班      |
+---------+-----------+
2 rows in set (0.00 sec)
mysql> insert into student values(100,"张三",1),(101,"李四",2);
Query OK, 2 rows affected (0.00 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> select * from student;
+-----------+-------------+---------+
| studentId | studentName | classId |
+-----------+-------------+---------+
|       100 | 张三        |       1 |
|       101 | 李四        |       2 |
+-----------+-------------+---------+
2 rows in set (0.00 sec)

Not only the insertion will be affected, but also the modification will be affected. If the value of the modified classId is not in the class table, an error will be reported.

mysql> select * from student;
+-----------+-------------+---------+
| studentId | studentName | classId |
+-----------+-------------+---------+
|       100 | 张三        |       1 |
|       101 | 李四        |       2 |
+-----------+-------------+-

mysql> update student set classId = 2 where studentId = 100;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from student;
+-----------+-------------+---------+
| studentId | studentName | classId |
+-----------+-------------+---------+
|       100 | 张三        |       2 |
|       101 | 李四        |       2 |
+-----------+-------------+---------+
2 rows in set (0.00 sec)
  1. Similarly, if I delete the data in the class table, an error will still be reported, because the data in it is associated with the student table and cannot be easily deleted.
mysql> select * from student;
+-----------+-------------+---------+
| studentId | studentName | classId |
+-----------+-------------+---------+
|         1 | zhangsan    |       1 |
|         2 | lisi        |       2 |
+-----------+-------------+---------+
2 rows in set (0.00 sec)

mysql> delete from  class where classId = 1;
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`base1`.`student`, CONSTRAINT `student_ibfk_1` FOREIGN KEY (`classId`) REFERENCES `class` (`classId`))

So what if I really need to delete this class record at this time?
For example, now that the class is being restructured, the record of the second class is deleted, but the student table remains unchanged as a stub. Then we are adding a column in the class table, marking it as deleted, which is actually logically deleted.

Guess you like

Origin blog.csdn.net/baixian110/article/details/131059725