[MySQL] Basics of adding, deleting, checking and modifying


Students who need cloud servers and other cloud products to learn Linux can move to / --> Tencent Cloud <-- / --> Alibaba Cloud <-- / --> Huawei Cloud <-- / official website, lightweight cloud servers are low-cost to 112 yuan/year, and new users can enjoy ultra-low discounts on their first order.


  Table of contents

1. Create

1. insert(insert)

1.1 Single row data insertion

1.2 Multi-row data insertion

1.3 Insert or replace updates

2.replace(replace)

2. Retrieve (read)

1、select

1.1 Full column query

1.2 Specify column query + use selsct to calculate expressions

1.3 Eliminate duplicates from screening results

2、where

2.1 Operators

2.2 Find students whose English score is less than 60 and their English scores

2.3 Students whose Chinese scores are [80, 90] and their Chinese scores

2.4 Students whose math scores are 58 or 59 or 98 or 99 and their math scores

2.5 Filter out classmates named Sun and classmates named Sun (fuzzy search)

2.6 Students whose Chinese scores are higher than their English scores

2.7 Students whose total score is below 200 points

2.8 Students whose Chinese scores are >80 and whose surname is not Sun

2.9 Student Sun, otherwise the total score is required to be > 200 and Chinese score < Mathematics score and English score > 80

2.10 NULL query

3. order by asc/desc (ascending/descending order of results)

3.1 Students and math scores are displayed in ascending/descending order according to math scores.

3.2 Query the scores of students in each subject, and display them in descending order of mathematics, descending order of English, and ascending order of Chinese.

3.3 Query classmates and total scores, from high to low

3.4 Query the math scores of students surnamed Sun or students surnamed Cao. The results will be displayed in order of math scores from high to low.

4. limit (screen a small number of results)

3. Update

1. Change Sun Wukong’s math score to 80 points

2. Change Cao Mengde’s math score to 60 points and his Chinese score to 70 points

3. Add 30 points to the math scores of the three students with the lowest total scores.

4. Update the Chinese scores of all students to twice the original value

4. Delete

1. Delete Sun Wukong’s test results

2. Delete the data of students with the highest total score

3. Delete the entire table data

3.1delete from

3.2 Truncate table (use with caution)

5. Insert the filtered data into the database (insert+select)

1. Delete duplicate records in the table. There can only be one copy of duplicate data.

6. Aggregation function

1. COUNT([DISTINCT] expr) returns the number of queried data

2. SUM([DISTINCT] expr) returns the sum of the queried data. It is meaningless if it is not a number.

3. AVG([DISTINCT] expr) returns the average value of the queried data. It is meaningless if it is not a number.

4. MAX([DISTINCT] expr) returns the maximum value of the queried data. It is meaningless if it is not a number.

5. MIN([DISTINCT] expr) returns the minimum value of the queried data. It is meaningless if it is not a number.

7. Group by clause: Group query on the specified column

1. Import employee information table

2. Display the average salary and maximum salary of each department

3. Display the average salary and minimum salary for each department and each position

4. Display the departments with an average salary below 2,000 and its average salary

5. 'Smith' does not participate in the statistics, which shows the types of work with an average salary of less than 2,000 for each department and each position.

5.1The difference between having and where


CRUD: Create, Retrieve, Update, Delete

1. Create

grammar:

INSERT [INTO] table_name
[(column [, column] ...)]
VALUES (value_list) [, (value_list)] ...
value_list: value, [, value] ...

First create a student table:

--创建学生表
mysql> create table if not exists students(
    -> id int unsigned primary key auto_increment,
    -> sn int unsigned unique key,
    -> name varchar(20) not null,
    -> qq varchar(32) unique key
    -> );
Query OK, 0 rows affected (0.31 sec)

1. insert(insert)

1.1 Single row data insertion

Insert a single row of a specified column:

mysql> insert into students (sn,name,qq) values (100,'张三','123456');
Query OK, 1 row affected (0.04 sec)

Single row and full column insertion:

mysql> insert into students values (2,101,'李四','222222');
Query OK, 1 row affected (0.05 sec)

1.2 Multi-row data insertion

mysql> insert into students (sn,name,qq) values (102,'王五','333333'),(103,'赵六',444444);
Query OK, 2 rows affected (0.04 sec)
Records: 2  Duplicates: 0  Warnings: 0

Each piece of data inserted is separated by commas to achieve the effect of inserting multiple rows at one time.

1.3 Insert or replace updates

--打印当前学生表数据
mysql> select* from students;
+----+------+--------+--------+
| id | sn   | name   | qq     |
+----+------+--------+--------+
|  1 |  100 | 张三   | 123456 |
|  2 |  101 | 李四   | 222222 |
|  3 |  102 | 王五   | 333333 |
|  4 |  103 | 赵六   | 444444 |
+----+------+--------+--------+
4 rows in set (0.00 sec)
--重复插入主键为2的值,主键冲突,插入失败
mysql> insert into students values (2,104,'小明','111111');
ERROR 1062 (23000): Duplicate entry '2' for key 'PRIMARY'
--插入变更新,注意作为更新的值可以和插入的值不一样
mysql> insert into students values (2,104,'小明',111111) on duplicate key update sn=104,name='小明',qq='111111';
Query OK, 2 rows affected (0.04 sec)
--打印当前学生表数据,发现id=2的数据被更新
mysql> select* from students;
+----+------+--------+--------+
| id | sn   | name   | qq     |
+----+------+--------+--------+
|  1 |  100 | 张三   | 123456 |
|  2 |  104 | 小明   | 111111 |
|  3 |  102 | 王五   | 333333 |
|  4 |  103 | 赵六   | 444444 |
+----+------+--------+--------+
4 rows in set (0.01 sec)

To insert data, first the data must be legal (the relevant fields are not constrained by unique keys, primary keys, foreign keys, etc.). Secondly, if the id of the inserted data already exists, sn, name and qq will be updated instead of the insertion failure.

2.replace(replace)

--如果替代的数据在表中无冲突,replace将被当成插入
mysql> replace into students (sn,name,qq) values (105,'小红','555555');
Query OK, 1 row affected (0.46 sec)
--打印当前学生表数据,可以看到表中多了一行小红的信息
mysql> select* from students;
+----+------+--------+--------+
| id | sn   | name   | qq     |
+----+------+--------+--------+
|  1 |  100 | 张三   | 123456 |
|  2 |  104 | 小明   | 111111 |
|  3 |  102 | 王五   | 333333 |
|  4 |  103 | 赵六   | 444444 |
|  5 |  105 | 小红   | 555555 |
+----+------+--------+--------+
5 rows in set (0.00 sec)
--再次replace,唯一键存在冲突,小红1的数据将替换小红的数据
mysql> replace into students (sn,name,qq) values (105,'小红1','555555');
Query OK, 2 rows affected (0.02 sec)
--打印当前学生表数据,发现小红1的id变为6
mysql> select* from students;
+----+------+---------+--------+
| id | sn   | name    | qq     |
+----+------+---------+--------+
|  1 |  100 | 张三    | 123456 |
|  2 |  104 | 小明    | 111111 |
|  3 |  102 | 王五    | 333333 |
|  4 |  103 | 赵六    | 444444 |
|  6 |  105 | 小红1   | 555555 |
+----+------+---------+--------+
5 rows in set (0.00 sec)

If there is no conflict in the primary key or unique key, insert it directly;

If the primary key or unique key conflicts, delete it and then insert it.

There is a detail: when a replacement occurs, because the primary key will increase automatically and replace is deleted and then replaced, the row id used for replacement will use the next self-increasing id. For example, in the above SQL statement, the original ID of Xiaohong is 5. After being replaced by Xiaohong1, the ID becomes 6.

2. Retrieve (read)

grammar:

SELECT
[DISTINCT] {* | {column [, column] ...}
[FROM table_name]
[WHERE ...]
[ORDER BY column [ASC | DESC], ...]
LIMIT ...

First create a score sheet:

--创建成绩表
mysql> CREATE TABLE exam_result (
    -> id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
    -> name VARCHAR(20) NOT NULL COMMENT '同学姓名',
    -> chinese float DEFAULT 0.0 COMMENT '语文成绩',
    -> math float DEFAULT 0.0 COMMENT '数学成绩',
    -> english float DEFAULT 0.0 COMMENT '英语成绩'
    -> );
Query OK, 0 rows affected (0.14 sec)
--插入测试数据
mysql> INSERT INTO exam_result (name, chinese, math, english) VALUES
    -> ('A', 67, 98, 56),
    -> ('B', 87, 78, 77),
    -> ('C', 88, 98, 90),
    -> ('D', 82, 84, 67),
    -> ('E', 55, 85, 45),
    -> ('F', 70, 73, 78),
    -> ('G', 75, 65, 30);
ds: 7 Duplicates: 0 Warnings: 0Query OK, 7 rows affected (0.03 sec)
Records: 7  Duplicates: 0  Warnings: 0

1、select

1.1 Full column query

mysql> select* from exam_result;
+----+------+---------+------+---------+
| id | name | chinese | math | english |
+----+------+---------+------+---------+
|  1 | A    |      67 |   98 |      56 |
|  2 | B    |      87 |   78 |      77 |
|  3 | C    |      88 |   98 |      90 |
|  4 | D    |      82 |   84 |      67 |
|  5 | E    |      55 |   85 |      45 |
|  6 | F    |      70 |   73 |      78 |
|  7 | G    |      75 |   65 |      30 |
+----+------+---------+------+---------+
7 rows in set (0.00 sec)

It is generally not recommended to use * for full column query

1. The more columns queried, the greater the amount of data that needs to be transmitted;

2. It may affect the use of indexes.

1.2 Specify column query + use selsct to calculate expressions

--指定姓名和数学成绩列进行查询
mysql> select name,math from exam_result;
+------+------+
| name | math |
+------+------+
| A    |   98 |
| B    |   78 |
| C    |   98 |
| D    |   84 |
| E    |   85 |
| F    |   73 |
| G    |   65 |
+------+------+
7 rows in set (0.00 sec)
--利用selsct计算平均分
mysql> select name,math,(chinese+math+english)/3 from exam_result;
+------+------+--------------------------+
| name | math | (chinese+math+english)/3 |
+------+------+--------------------------+
| A    |   98 |        73.66666666666667 |
| B    |   78 |        80.66666666666667 |
| C    |   98 |                       92 |
| D    |   84 |        77.66666666666667 |
| E    |   85 |       61.666666666666664 |
| F    |   73 |        73.66666666666667 |
| G    |   65 |       56.666666666666664 |
+------+------+--------------------------+

--觉得计算式太长,可以用as给它重命名为average
mysql> select name,math,(chinese+math+english)/3 as average from exam_result;
+------+------+--------------------+
| name | math | average            |
+------+------+--------------------+
| A    |   98 |  73.66666666666667 |
| B    |   78 |  80.66666666666667 |
| C    |   98 |                 92 |
| D    |   84 |  77.66666666666667 |
| E    |   85 | 61.666666666666664 |
| F    |   73 |  73.66666666666667 |
| G    |   65 | 56.666666666666664 |
+------+------+--------------------+
7 rows in set (0.02 sec)

--当然这个as可以省略
mysql> select name 姓名,math 数学,(chinese+math+english)/3 平均分 from exam_result;
+--------+--------+--------------------+
| 姓名   | 数学    | 平均分             |
+--------+--------+--------------------+
| A      |     98 |  73.66666666666667 |
| B      |     78 |  80.66666666666667 |
| C      |     98 |                 92 |
| D      |     84 |  77.66666666666667 |
| E      |     85 | 61.666666666666664 |
| F      |     73 |  73.66666666666667 |
| G      |     65 | 56.666666666666664 |
+--------+--------+--------------------+
7 rows in set (0.01 sec)

1.3 Eliminate duplicates from screening results

mysql> select distinct math from exam_result;
+------+
| math |
+------+
|   98 |
|   78 |
|   84 |
|   85 |
|   73 |
|   65 |
+------+
6 rows in set (0.00 sec)

2、where

2.1 Operators

Comparison operators:

operator

illustrate

>, >=, <, <=

Greater than, greater than or equal to, less than, less than or equal to

=

Equal to, NULL is unsafe , for example, the result of NULL = NULL is NULL

<=>

Equal to, NULL is safe, for example, the result of NULL <=> NULL is TRUE(1)

!=, <>

Not equal to (both symbols are NULL unsafe)

BETWEEN a0 AND a1

Range match, [a0, a1], if a0 <= value <= a1, return TRUE(1)

IN (option, ...)

If it is any one of the options, return TRUE(1)

IS NULL

is NULL

IS NOT NULL

Not NULL

LIKE

Fuzzy matching. like 'A%'. % represents any number (including 0) of any character; like 'A_'. _ represents any character

Logical Operators:

operator

illustrate

AND

Multiple conditions must all be TRUE(1), and the result is TRUE(1)

OR

If any condition is TRUE(1), the result is TRUE(1)

NOT

The condition is TRUE(1), the result is FALSE(0)

2.2 Find students whose English score is less than 60 and their English scores

mysql> select name,english from exam_result where english<60;
+------+---------+
| name | english |
+------+---------+
| A    |      56 |
| E    |      45 |
| G    |      30 |
+------+---------+
3 rows in set (0.00 sec)

2.3 Students whose Chinese scores are [80, 90] and their Chinese scores

--  >=和<=
mysql> select name,chinese from exam_result where chinese>=80 and chinese <=90;
+------+---------+
| name | chinese |
+------+---------+
| B    |      87 |
| C    |      88 |
| D    |      82 |
+------+---------+
3 rows in set (0.01 sec)

--between a0 and a1
mysql> select name,chinese from exam_result where chinese between 80 and 90;
+------+---------+
| name | chinese |
+------+---------+
| B    |      87 |
| C    |      88 |
| D    |      82 |
+------+---------+
3 rows in set (0.00 sec)

2.4 Students whose math scores are 58 or 59 or 98 or 99 and their math scores

--可以采用多个or
mysql> select name,math from exam_result where math=58 or math=59 or math=98 or math=99;
+------+------+
| name | math |
+------+------+
| A    |   98 |
| C    |   98 |
+------+------+
2 rows in set (0.02 sec)

--可以用in(......)
mysql> select name,math from exam_result where math in(58,59,98,99);
+------+------+
| name | math |
+------+------+
| A    |   98 |
| C    |   98 |
+------+------+
2 rows in set (0.00 sec)

2.5 Filter out classmates named Sun and classmates named Sun (fuzzy search)

--对新表插入数据
INSERT INTO exam_result (name, chinese, math, english) VALUES
('唐三藏', 67, 98, 56),
('孙悟空', 87, 78, 77),
('猪悟能', 88, 98, 90),
('曹孟德', 82, 84, 67),
('刘玄德', 55, 85, 45),
('孙权', 70, 73, 78),
('宋公明', 75, 65, 30);
-- like '孙%'找到所有孙姓同学,%代表后面模糊匹配0-n个字符
mysql> select name from exam_result where name like '孙%';
+-----------+
| name      |
+-----------+
| 孙悟空    |
| 孙权      |
+-----------+
2 rows in set (0.00 sec)

--like '孙_'找到所有孙某同学,_代表模糊匹配1个字符
mysql> select name from exam_result where name like '孙_';
+--------+
| name   |
+--------+
| 孙权   |
+--------+
1 row in set (0.00 sec)

2.6 Students whose Chinese scores are higher than their English scores

mysql> select name,chinese,english from exam_result where chinese>english;
+-----------+---------+---------+
| name      | chinese | english |
+-----------+---------+---------+
| 唐三藏    |      67 |      56 |
| 孙悟空    |      87 |      77 |
| 曹孟德    |      82 |      67 |
| 刘玄德    |      55 |      45 |
| 宋公明    |      75 |      30 |
+-----------+---------+---------+
5 rows in set (0.00 sec)

2.7 Students whose total score is below 200 points

mysql> select name,chinese,math,english,chinese+math+english 总分 from exam_result where chinese+math+english<200;
+-----------+---------+------+---------+--------+
| name      | chinese | math | english | 总分   |
+-----------+---------+------+---------+--------+
| 刘玄德    |      55 |   85 |      45 |    185 |
| 宋公明    |      75 |   65 |      30 |    170 |
+-----------+---------+------+---------+--------+
2 rows in set (0.00 sec)

The execution sequence of this SQL is shown in the figure above. Therefore, it is not possible to directly use the total score after where to express chinese+math+english. (Go to the exam_result table to find students whose chinese+math+english is less than 200 and print it)

2.8 Students whose Chinese scores are >80 and whose surname is not Sun

mysql> select name,chinese from exam_result where chinese>80 and name not like '孙%';
+-----------+---------+
| name      | chinese |
+-----------+---------+
| 猪悟能    |      88 |
| 曹孟德    |      82 |
+-----------+---------+
2 rows in set (0.00 sec)

2.9 Student Sun, otherwise the total score is required to be > 200 and Chinese score < Mathematics score and English score > 80

mysql> select name,chinese,math,english,chinese+math+english 总分 from exam_result where name like '孙_' or (chinese+math+english>200 and chinese<math and english>80);
+-----------+---------+------+---------+--------+
| name      | chinese | math | english | 总分   |
+-----------+---------+------+---------+--------+
| 猪悟能    |      88 |   98 |      90 |    276 |
| 孙权      |      70 |   73 |      78 |    221 |
+-----------+---------+------+---------+--------+
2 rows in set (0.00 sec)

2.10 NULL query

--创建一个新表
mysql> create table test(
    -> id int,
    ->  name varchar(20)
    -> );
Query OK, 0 rows affected (0.09 sec)

--插入数据
mysql> insert into test (id,name) values (1,'张三');
Query OK, 1 row affected (0.04 sec)
mysql> insert into test (id,name) values (null,'张三');
Query OK, 1 row affected (0.05 sec)
mysql> insert into test (id,name) values (1,null);
Query OK, 1 row affected (0.05 sec)
mysql> insert into test (id,name) values (null,null);
Query OK, 1 row affected (0.02 sec)
mysql> insert into test (id,name) values (1,'');
Query OK, 1 row affected (0.01 sec)
--打印表结构
mysql> select* from test;
+------+--------+
| id   | name   |
+------+--------+
|    1 | 张三   |
| NULL | 张三   |
|    1 | NULL   |
| NULL | NULL   |
|    1 |        |
+------+--------+
5 rows in set (0.02 sec)

null query:

mysql> select* from test where name is null;
+------+------+
| id   | name |
+------+------+
|    1 | NULL |
| NULL | NULL |
+------+------+
2 rows in set (0.01 sec)

mysql> select* from test where name is not null;
+------+--------+
| id   | name   |
+------+--------+
|    1 | 张三   |
| NULL | 张三   |
|    1 |        |
+------+--------+
3 rows in set (0.01 sec)

Note: null is null, and an empty string is an empty string, which is different.

mysql> SELECT NULL = NULL, NULL = 1, NULL = 0;
+-------------+----------+----------+
| NULL = NULL | NULL = 1 | NULL = 0 |
+-------------+----------+----------+
|        NULL |     NULL |     NULL |
+-------------+----------+----------+
1 row in set (0.00 sec)

mysql> SELECT NULL <=> NULL, NULL <=> 1, NULL <=> 0;
+---------------+------------+------------+
| NULL <=> NULL | NULL <=> 1 | NULL <=> 0 |
+---------------+------------+------------+
|             1 |          0 |          0 |
+---------------+------------+------------+
1 row in set (0.01 sec)

Comparison between nulls cannot use =, you must use <=> or is null or is not null

3. order by asc/desc (ascending/descending order of results)

3.1 Students and math scores are displayed in ascending/descending order according to math scores.

mysql> select name,math from exam_result order by math asc;
+-----------+------+
| name      | math |
+-----------+------+
| 张三      | NULL |
| 宋公明    |   65 |
| 孙权      |   73 |
| 孙悟空    |   78 |
| 曹孟德    |   84 |
| 刘玄德    |   85 |
| 唐三藏    |   98 |
| 猪悟能    |   98 |
+-----------+------+
8 rows in set (0.00 sec)

mysql> select name,math from exam_result order by math desc;
+-----------+------+
| name      | math |
+-----------+------+
| 唐三藏    |   98 |
| 猪悟能    |   98 |
| 刘玄德    |   85 |
| 曹孟德    |   84 |
| 孙悟空    |   78 |
| 孙权      |   73 |
| 宋公明    |   65 |
| 张三      | NULL |
+-----------+------+
8 rows in set (0.00 sec)

-- ASC is ascending order (from small to large)

-- DESC is descending order (from large to small)

-- Default is ASC

-- NULL is treated as less than any value

3.2 Query the scores of students in each subject, and display them in descending order of mathematics, descending order of English, and ascending order of Chinese.

mysql> select name,math,english,chinese from exam_result order by math desc,english desc,chinese asc;
+-----------+------+---------+---------+
| name      | math | english | chinese |
+-----------+------+---------+---------+
| 猪悟能    |   98 |      90 |      88 |
| 唐三藏    |   98 |      56 |      67 |
| 刘玄德    |   85 |      45 |      55 |
| 曹孟德    |   84 |      67 |      82 |
| 孙悟空    |   78 |      77 |      87 |
| 孙权      |   73 |      78 |      70 |
| 宋公明    |   65 |      30 |      75 |
| 张三      | NULL |    NULL |    NULL |
+-----------+------+---------+---------+
8 rows in set (0.00 sec)

3.3 Query classmates and total scores, from high to low

mysql> select name,chinese,math,english,chinese+math+english 总分 from exam_result order by 总分 desc;
+-----------+---------+------+---------+--------+
| name      | chinese | math | english | 总分   |
+-----------+---------+------+---------+--------+
| 猪悟能    |      88 |   98 |      90 |    276 |
| 孙悟空    |      87 |   78 |      77 |    242 |
| 曹孟德    |      82 |   84 |      67 |    233 |
| 唐三藏    |      67 |   98 |      56 |    221 |
| 孙权      |      70 |   73 |      78 |    221 |
| 刘玄德    |      55 |   85 |      45 |    185 |
| 宋公明    |      75 |   65 |      30 |    170 |
| 张三      |    NULL | NULL |    NULL |   NULL |
+-----------+---------+------+---------+--------+
8 rows in set (0.00 sec)

mysql> 

The above where statement cannot use aliases. But aliases can be used here because of the order issue.

First priority: Make it clear which table exam_result you are looking for

Second priority: where clause

Third priority: chinese+math+english total score

Fourth priority: order by total score desc (please have appropriate data before sorting)

Fifth priority: limit (data will be displayed only when it is ready)

3.4 Query the math scores of students surnamed Sun or students surnamed Cao. The results will be displayed in order of math scores from high to low.

mysql> select name,math from exam_result where name like '孙%' or name like '曹%' order by math desc limit 3 offset 0;
+-----------+------+
| name      | math |
+-----------+------+
| 曹孟德    |   84 |
| 孙悟空    |   78 |
| 孙权      |   73 |
+-----------+------+
3 rows in set (0.00 sec)

4. limit (screen a small number of results)

--从表开始连续读取5行
mysql> select* from exam_result limit 5;
+----+-----------+---------+------+---------+
| id | name      | chinese | math | english |
+----+-----------+---------+------+---------+
|  1 | 唐三藏    |      67 |   98 |      56 |
|  2 | 孙悟空    |      87 |   78 |      77 |
|  3 | 猪悟能    |      88 |   98 |      90 |
|  4 | 曹孟德    |      82 |   84 |      67 |
|  5 | 刘玄德    |      55 |   85 |      45 |
+----+-----------+---------+------+---------+
5 rows in set (0.01 sec)

--limit 1,3;开始位置1是下标,3是步长
mysql> select* from exam_result limit 1,3;
+----+-----------+---------+------+---------+
| id | name      | chinese | math | english |
+----+-----------+---------+------+---------+
|  2 | 孙悟空    |      87 |   78 |      77 |
|  3 | 猪悟能    |      88 |   98 |      90 |
|  4 | 曹孟德    |      82 |   84 |      67 |
+----+-----------+---------+------+---------+
3 rows in set (0.01 sec)

--limit s offset n其中s代表步长,n代表下标
mysql> select* from exam_result limit 3 offset 5;
+----+-----------+---------+------+---------+
| id | name      | chinese | math | english |
+----+-----------+---------+------+---------+
|  6 | 孙权      |      70 |   73 |      78 |
|  7 | 宋公明    |      75 |   65 |      30 |
|  8 | 张三      |    NULL | NULL |    NULL |
+----+-----------+---------+------+---------+
3 rows in set (0.00 sec)

When querying an unknown table, it is best to add a LIMIT 1 to avoid the database being stuck due to querying the entire table data because the data in the table is too large.

select* from exam_result limit 0,3;

select* from exam_result limit 3,3;

select* from exam_result limit 6,3;

......

select* from exam_result limit 3 offset 0;

select* from exam_result limit 3 offset 3;

select* from exam_result limit 3 offset 6;

Perform paginated display.

3. Update

grammar:

UPDATE table_name SET column = expr [, column = expr ...]
[WHERE ...] [ORDER BY ...] [LIMIT ...]

1. Change Sun Wukong’s math score to 80 points

mysql> update exam_result set math=80 where name ='孙悟空';
Query OK, 1 row affected (0.07 sec)

2. Change Cao Mengde’s math score to 60 points and his Chinese score to 70 points

mysql> update exam_result set math=60,chinese=70 where name ='曹孟德';
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

3. Add 30 points to the math scores of the three students with the lowest total scores.

mysql> update exam_result set math=math+30 order by chinese+math+english asc limit 3;
Query OK, 2 rows affected (0.05 sec)
Rows matched: 3  Changed: 2  Warnings: 0

4. Update the Chinese scores of all students to twice the original value

mysql> update exam_result set chinese=chinese*2;
Query OK, 7 rows affected (0.04 sec)
Rows matched: 8  Changed: 7  Warnings: 0

mysql> select * from exam_result;
+----+-----------+---------+------+---------+
| id | name      | chinese | math | english |
+----+-----------+---------+------+---------+
|  1 | 唐三藏    |     134 |   98 |      56 |
|  2 | 孙悟空    |     174 |   80 |      77 |
|  3 | 猪悟能    |     176 |   98 |      90 |
|  4 | 曹孟德    |     140 |   60 |      67 |
|  5 | 刘玄德    |     110 |  115 |      45 |
|  6 | 孙权      |     140 |   73 |      78 |
|  7 | 宋公明    |     150 |   95 |      30 |
|  8 | 张三      |    NULL | NULL |    NULL |
+----+-----------+---------+------+---------+
8 rows in set (0.00 sec)

Be careful when directly updating the entire table without a where clause! A wrong update is as harmful as a delete.

4. Delete

grammar:

DELETE FROM table_name [WHERE ...] [ORDER BY ...] [LIMIT ...]

1. Delete Sun Wukong’s test results

mysql> delete from exam_result where name='孙悟空';
Query OK, 1 row affected (0.04 sec)

mysql> select * from exam_result;
+----+-----------+---------+------+---------+
| id | name      | chinese | math | english |
+----+-----------+---------+------+---------+
|  1 | 唐三藏    |     134 |   98 |      56 |
|  3 | 猪悟能    |     176 |   98 |      90 |
|  4 | 曹孟德    |     140 |   60 |      67 |
|  5 | 刘玄德    |     110 |  115 |      45 |
|  6 | 孙权      |     140 |   73 |      78 |
|  7 | 宋公明    |     150 |   95 |      30 |
|  8 | 张三      |    NULL | NULL |    NULL |
+----+-----------+---------+------+---------+
7 rows in set (0.00 sec)

2. Delete the data of students with the highest total score

mysql> delete from exam_result order by chinese+math+english desc limit 1;
Query OK, 1 row affected (0.02 sec)

3. Delete the entire table data

3.1delete from

--准备测试表
mysql> CREATE TABLE for_delete (
    -> id INT PRIMARY KEY AUTO_INCREMENT,
    -> name VARCHAR(20)
    -> );
Query OK, 0 rows affected (0.15 sec)
--插入测试数据
mysql> INSERT INTO for_delete (name) VALUES ('A'), ('B'), ('C');
Query OK, 3 rows affected (0.04 sec)
Records: 3  Duplicates: 0  Warnings: 0
--查看表结构
mysql> select* from for_delete;
+----+------+
| id | name |
+----+------+
|  1 | A    |
|  2 | B    |
|  3 | C    |
+----+------+
3 rows in set (0.00 sec)
--查看创建表时的SQL,可以发现,下一次自增的id值是4
mysql> show create table for_delete\G;
*************************** 1. row ***************************
       Table: for_delete
Create Table: CREATE TABLE `for_delete` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=gbk
1 row in set (0.00 sec)
--删除表
mysql> delete from for_delete;
Query OK, 3 rows affected (0.04 sec)
--查看创建表的SQL,发现自增值仍为4
mysql> show create table for_delete\G;
*************************** 1. row ***************************
       Table: for_delete
Create Table: CREATE TABLE `for_delete` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=gbk
1 row in set (0.02 sec)

Using deselect from to clear the contents of the table will not change the auto-increment value.

3.2 Truncate table (use with caution)

grammar:

TRUNCATE [TABLE] table_name
--准备测试表
mysql> CREATE TABLE for_truncate (
    -> id INT PRIMARY KEY AUTO_INCREMENT,
    -> name VARCHAR(20)
    -> );
Query OK, 0 rows affected (0.14 sec)
--插入测试数据
mysql> INSERT INTO for_truncate (name) VALUES ('A'), ('B'), ('C');
Query OK, 3 rows affected (0.04 sec)
Records: 3  Duplicates: 0  Warnings: 0
--查看表结构
mysql> select* from for_truncate;
+----+------+
| id | name |
+----+------+
|  1 | A    |
|  2 | B    |
|  3 | C    |
+----+------+
3 rows in set (0.01 sec)
--查看创建表时的SQL,可以发现,下一次自增的id值是4
5mysql> show create table for_truncate\G;
*************************** 1. row ***************************
       Table: for_truncate
Create Table: CREATE TABLE `for_truncate` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=gbk
1 row in set (0.01 sec)
--删除表中数据
mysql> truncate for_truncate;
Query OK, 0 rows affected (0.21 sec)
--查看创建表时的SQL,发现AUTO_INCREMENT字段没了
mysql> show create table for_truncate\G;
*************************** 1. row ***************************
       Table: for_truncate
Create Table: CREATE TABLE `for_truncate` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk
1 row in set (0.01 sec)
--新插入一条数据
mysql>  insert into for_truncate (name) values ('E');
Query OK, 1 row affected (0.04 sec)
--查看表结构,发现id从1开始
mysql> select* from for_truncate;
+----+------+
| id | name |
+----+------+
|  1 | E    |
+----+------+
1 row in set (0.00 sec)
--查看创建表的SQL,出现自增字段,下一次自增值是2
mysql> show create table for_truncate\G;
*************************** 1. row ***************************
       Table: for_truncate
Create Table: CREATE TABLE `for_truncate` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=gbk
1 row in set (0.00 sec)

Use truncate operation with caution

1. It can only operate on the entire table, and cannot operate on partial data like DELETE;

2. MySQL does not record truncate operation records in the log (DELETE does), so it is faster than DELETE. However, when TRUNCATE deletes data, it does not go through the real thing, so it cannot be rolled back.

3. When truncate clears the table, it will initialize the auto-increment value.

5. Insert the filtered data into the database (insert+select)

INSERT INTO table_name [(column [, column ...])] SELECT ...

1. Delete duplicate records in the table. There can only be one copy of duplicate data.

Create a copy of raw data:

--创建表结构
mysql> CREATE TABLE duplicate_table (id int, name varchar(20));
Query OK, 0 rows affected (0.26 sec)
--插入测试数据
mysql> INSERT INTO duplicate_table VALUES
    -> (100, 'aaa'),
    -> (100, 'aaa'),
    -> (200, 'bbb'),
    -> (200, 'bbb'),
    -> (200, 'bbb'),
    -> (300, 'ccc');
Query OK, 6 rows affected (0.03 sec)
Records: 6  Duplicates: 0  Warnings: 0

Ideas for deduplication: 1. Create an empty table with the same attributes as the original table

--创建一张属性和duplicate_table一样的表no_duplicate_table(空表)
mysql> create table no_duplicate_table like duplicate_table;
Query OK, 0 rows affected (0.23 sec)
--它是空表
mysql> select* from no_duplicate_table;
Empty set (0.01 sec)
--但是属性和duplicate_table一样
mysql> desc no_duplicate_table;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(11)     | YES  |     | NULL    |       |
| name  | varchar(20) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.02 sec)

2. Use distinct to filter out the deduplicated data in the original table.

--对原表select出来的结果insert进新表中
mysql> insert into no_duplicate_table select distinct * from duplicate_table;
Query OK, 3 rows affected (0.05 sec)
Records: 3  Duplicates: 0  Warnings: 0
--查看新表数据
mysql> select* from no_duplicate_table;
+------+------+
| id   | name |
+------+------+
|  100 | aaa  |
|  200 | bbb  |
|  300 | ccc  |
+------+------+
3 rows in set (0.01 sec)

3. Change the name of the original table to something else, and change the data of the new table to the name of the original table (the raccoon cat is replaced by the prince).

--改名
mysql> rename table duplicate_table to old_duplicate_table,no_duplicate_table to duplicate_table;
Query OK, 0 rows affected (0.17 sec)
--查看表
mysql> select* from duplicate_table;
+------+------+
| id   | name |
+------+------+
|  100 | aaa  |
|  200 | bbb  |
|  300 | ccc  |
+------+------+
3 rows in set (0.02 sec)

We have prepared the new table before renaming it. By renaming the table, we can achieve atomic deduplication operation.

The rename here is simply a name change, which is actually a change in the mapping relationship between the file name and the inode.

6. Aggregation function

function

illustrate

COUNT([DISTINCT] expr)

Returns the number of queried data

SUM([DISTINCT] expr)

Returns the sum of the queried data. It is meaningless if it is not a number.

AVG([DISTINCT] expr)

Returns the average value of the queried data. It is meaningless if it is not a number.

MAX([DISTINCT] expr)

Returns the maximum value of the queried data. It is meaningless if it is not a number.

MIN([DISTINCT] expr)

Returns the minimum value of the queried data. It is meaningless if it is not a number.

1. COUNT([DISTINCT] expr) returns the number of queried data

mysql> select* from old_duplicate_table;;
+------+------+
| id   | name |
+------+------+
|  100 | aaa  |
|  100 | aaa  |
|  200 | bbb  |
|  200 | bbb  |
|  200 | bbb  |
|  300 | ccc  |
+------+------+
6 rows in set (0.01 sec)
--统计去重的名字有几个
mysql> select count(distinct name) 总数 from old_duplicate_table;
+--------+
| 总数   |
+--------+
|      3 |
+--------+
1 row in set (0.00 sec)
--统计共有几行
mysql> select count(*) from old_duplicate_table;
+----------+
| count(*) |
+----------+
|        6 |
+----------+
1 row in set (0.00 sec)
--统计共有几行
mysql> select count(2) from old_duplicate_table;
+----------+
| count(2) |
+----------+
|        6 |
+----------+
1 row in set (0.00 sec)
--统计id小于200的行数
mysql> select count(*) from old_duplicate_table where id<200;
+----------+
| count(*) |
+----------+
|        2 |
+----------+
1 row in set (0.01 sec)

2. SUM([DISTINCT] expr) returns the sum of the queried data. It is meaningless if it is not a number.

--统计id和
mysql> select sum(id) from old_duplicate_table;
+---------+
| sum(id) |
+---------+
|    1100 |
+---------+
1 row in set (0.00 sec)
--统计id的平均值
mysql> select sum(id)/count(*) from old_duplicate_table;
+------------------+
| sum(id)/count(*) |
+------------------+
|         183.3333 |
+------------------+
1 row in set (0.00 sec)

3. AVG([DISTINCT] expr) returns the average value of the queried data. It is meaningless if it is not a number.

--统计id的平均值
mysql> select avg(id) from old_duplicate_table;
+----------+
| avg(id)  |
+----------+
| 183.3333 |
+----------+
1 row in set (0.00 sec)

4. MAX([DISTINCT] expr) returns the maximum value of the queried data. It is meaningless if it is not a number.

4、MAX([DISTINCT] expr) 返回查询到的数据的 最大值,不是数字没有意义

5. MIN([DISTINCT] expr) returns the minimum value of the queried data. It is meaningless if it is not a number.

--查找最小的id
mysql> select min(id) from old_duplicate_table;
+---------+
| min(id) |
+---------+
|     100 |
+---------+
1 row in set (0.01 sec)
--查找id大于150的最小值
mysql> select min(id) from old_duplicate_table where id>150;
+---------+
| min(id) |
+---------+
|     200 |
+---------+
1 row in set (0.00 sec)

7. Group by clause: Group query on the specified column

The purpose of grouping is to aggregate statistics.

select column1, column2, .. from table group by column;

1. Import employee information table

--将linux目录下的sql表导入MySQL
mysql> source /home/jly/scott_data.sql;

mysql> use scott;
Database changed

mysql> show tables;
+-----------------+
| Tables_in_scott |
+-----------------+
| dept            |
| emp             |
| salgrade        |
+-----------------+

Create an employee information table (classic test table from oracle 9i)

EMP employee list

DEPT department table

SALGRADE salary scale

DROP database IF EXISTS `scott`;
CREATE database IF NOT EXISTS `scott` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

USE `scott`;

DROP TABLE IF EXISTS `dept`;
CREATE TABLE `dept` (
  `deptno` int(2) unsigned zerofill NOT NULL COMMENT '部门编号',
  `dname` varchar(14) DEFAULT NULL COMMENT '部门名称',
  `loc` varchar(13) DEFAULT NULL COMMENT '部门所在地点'
);


DROP TABLE IF EXISTS `emp`;
CREATE TABLE `emp` (
  `empno` int(6) unsigned zerofill NOT NULL COMMENT '雇员编号',
  `ename` varchar(10) DEFAULT NULL COMMENT '雇员姓名',
  `job` varchar(9) DEFAULT NULL COMMENT '雇员职位',
  `mgr` int(4) unsigned zerofill DEFAULT NULL COMMENT '雇员领导编号',
  `hiredate` datetime DEFAULT NULL COMMENT '雇佣时间',
  `sal` decimal(7,2) DEFAULT NULL COMMENT '工资月薪',
  `comm` decimal(7,2) DEFAULT NULL COMMENT '奖金',
  `deptno` int(2) unsigned zerofill DEFAULT NULL COMMENT '部门编号'
);


DROP TABLE IF EXISTS `salgrade`;
CREATE TABLE `salgrade` (
  `grade` int(11) DEFAULT NULL COMMENT '等级',
  `losal` int(11) DEFAULT NULL COMMENT '此等级最低工资',
  `hisal` int(11) DEFAULT NULL COMMENT '此等级最高工资'
);


insert into dept (deptno, dname, loc)
values (10, 'ACCOUNTING', 'NEW YORK');
insert into dept (deptno, dname, loc)
values (20, 'RESEARCH', 'DALLAS');
insert into dept (deptno, dname, loc)
values (30, 'SALES', 'CHICAGO');
insert into dept (deptno, dname, loc)
values (40, 'OPERATIONS', 'BOSTON');

insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno)
values (7369, 'SMITH', 'CLERK', 7902, '1980-12-17', 800, null, 20);

insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno)
values (7499, 'ALLEN', 'SALESMAN', 7698, '1981-02-20', 1600, 300, 30);

insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno)
values (7521, 'WARD', 'SALESMAN', 7698, '1981-02-22', 1250, 500, 30);

insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno)
values (7566, 'JONES', 'MANAGER', 7839, '1981-04-02', 2975, null, 20);

insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno)
values (7654, 'MARTIN', 'SALESMAN', 7698, '1981-09-28', 1250, 1400, 30);

insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno)
values (7698, 'BLAKE', 'MANAGER', 7839, '1981-05-01', 2850, null, 30);

insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno)
values (7782, 'CLARK', 'MANAGER', 7839, '1981-06-09', 2450, null, 10);

insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno)
values (7788, 'SCOTT', 'ANALYST', 7566, '1987-04-19', 3000, null, 20);

insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno)
values (7839, 'KING', 'PRESIDENT', null, '1981-11-17', 5000, null, 10);

insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno)
values (7844, 'TURNER', 'SALESMAN', 7698,'1981-09-08', 1500, 0, 30);

insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno)
values (7876, 'ADAMS', 'CLERK', 7788, '1987-05-23', 1100, null, 20);

insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno)
values (7900, 'JAMES', 'CLERK', 7698, '1981-12-03', 950, null, 30);

insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno)
values (7902, 'FORD', 'ANALYST', 7566, '1981-12-03', 3000, null, 20);

insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno)
values (7934, 'MILLER', 'CLERK', 7782, '1982-01-23', 1300, null, 10);

insert into salgrade (grade, losal, hisal) values (1, 700, 1200);
insert into salgrade (grade, losal, hisal) values (2, 1201, 1400);
insert into salgrade (grade, losal, hisal) values (3, 1401, 2000);
insert into salgrade (grade, losal, hisal) values (4, 2001, 3000);
insert into salgrade (grade, losal, hisal) values (5, 3001, 9999);

2. Display the average salary and maximum salary of each department

mysql> select* from emp;
+--------+--------+-----------+------+---------------------+---------+---------+--------+
| empno  | ename  | job       | mgr  | hiredate            | sal     | comm    | deptno |
+--------+--------+-----------+------+---------------------+---------+---------+--------+
| 007369 | SMITH  | CLERK     | 7902 | 1980-12-17 00:00:00 |  800.00 |    NULL |     20 |
| 007499 | ALLEN  | SALESMAN  | 7698 | 1981-02-20 00:00:00 | 1600.00 |  300.00 |     30 |
| 007521 | WARD   | SALESMAN  | 7698 | 1981-02-22 00:00:00 | 1250.00 |  500.00 |     30 |
| 007566 | JONES  | MANAGER   | 7839 | 1981-04-02 00:00:00 | 2975.00 |    NULL |     20 |
| 007654 | MARTIN | SALESMAN  | 7698 | 1981-09-28 00:00:00 | 1250.00 | 1400.00 |     30 |
| 007698 | BLAKE  | MANAGER   | 7839 | 1981-05-01 00:00:00 | 2850.00 |    NULL |     30 |
| 007782 | CLARK  | MANAGER   | 7839 | 1981-06-09 00:00:00 | 2450.00 |    NULL |     10 |
| 007788 | SCOTT  | ANALYST   | 7566 | 1987-04-19 00:00:00 | 3000.00 |    NULL |     20 |
| 007839 | KING   | PRESIDENT | NULL | 1981-11-17 00:00:00 | 5000.00 |    NULL |     10 |
| 007844 | TURNER | SALESMAN  | 7698 | 1981-09-08 00:00:00 | 1500.00 |    0.00 |     30 |
| 007876 | ADAMS  | CLERK     | 7788 | 1987-05-23 00:00:00 | 1100.00 |    NULL |     20 |
| 007900 | JAMES  | CLERK     | 7698 | 1981-12-03 00:00:00 |  950.00 |    NULL |     30 |
| 007902 | FORD   | ANALYST   | 7566 | 1981-12-03 00:00:00 | 3000.00 |    NULL |     20 |
| 007934 | MILLER | CLERK     | 7782 | 1982-01-23 00:00:00 | 1300.00 |    NULL |     10 |
+--------+--------+-----------+------+---------------------+---------+---------+--------+
14 rows in set (0.00 sec)
--按部门对各部门的平均工资和最高工资进行统计
mysql> select deptno,avg(sal),max(sal) from emp group by deptno;
+--------+-------------+----------+
| deptno | avg(sal)    | max(sal) |
+--------+-------------+----------+
|     10 | 2916.666667 |  5000.00 |
|     20 | 2175.000000 |  3000.00 |
|     30 | 1566.666667 |  2850.00 |
+--------+-------------+----------+
3 rows in set (0.01 sec)

3. Display the average salary and minimum salary for each department and each position

Group query with multiple grouping conditions:

mysql> select deptno,job,avg(sal),max(sal) from emp group by deptno,job;
+--------+-----------+-------------+----------+
| deptno | job       | avg(sal)    | max(sal) |
+--------+-----------+-------------+----------+
|     10 | CLERK     | 1300.000000 |  1300.00 |
|     10 | MANAGER   | 2450.000000 |  2450.00 |
|     10 | PRESIDENT | 5000.000000 |  5000.00 |
|     20 | ANALYST   | 3000.000000 |  3000.00 |
|     20 | CLERK     |  950.000000 |  1100.00 |
|     20 | MANAGER   | 2975.000000 |  2975.00 |
|     30 | CLERK     |  950.000000 |   950.00 |
|     30 | MANAGER   | 2850.000000 |  2850.00 |
|     30 | SALESMAN  | 1400.000000 |  1600.00 |
+--------+-----------+-------------+----------+
9 rows in set (0.00 sec)

If you add an ename filter field after the select filter, an error will be reported:

4. Display the departments with an average salary below 2,000 and its average salary

1. First, count the average salary of each department (first group and aggregate the average salary by department)

2. Then use having to conditionally judge the aggregation results.

mysql> select deptno,avg(sal) as 平均工资 from emp group by deptno having 平均工资<2000;
+--------+--------------+
| deptno | 平均工资     |
+--------+--------------+
|     30 |  1566.666667 |
+--------+--------------+

5. 'Smith' does not participate in the statistics, which shows the types of work with an average salary of less than 2,000 for each department and each position.

mysql> select deptno,job,avg(sal) 平均工资 from emp where ename!='SMITH' group by deptno,job having 平均工资<2000;
+--------+----------+--------------+
| deptno | job      | 平均工资     |
+--------+----------+--------------+
|     10 | CLERK    |  1300.000000 |
|     20 | CLERK    |  1100.000000 |
|     30 | CLERK    |   950.000000 |
|     30 | SALESMAN |  1400.000000 |
+--------+----------+--------------+
4 rows in set (0.01 sec)

5.1The difference between having and where

1. Both having and where can be used for conditional filtering. Group aggregation can only use having and not where. However, for filtering with only one table, both having and where can be used. However, it is not recommended to use having in this scenario (in order to distinguish, it is not recommended to use having). It is recommended to mix them, and let where do the work of where)

2. The objects of screening are different, as shown below:

3. The order of condition filtering is different, as shown below:

Guess you like

Origin blog.csdn.net/gfdxx/article/details/131297229