当前位置: 首页 > news >正文

掌握MySQL:基本查询指令与技巧

🍑个人主页:Jupiter.
🚀 所属专栏:MySQL初阶学习笔记
欢迎大家点赞收藏评论😊

在这里插入图片描述

在这里插入图片描述

目录

  • `表的增删查改`
      • `1 Create`
        • `Insert`
        • `1.1 单行数据 + 全列插入+指定列插入`
        • `1.2 多行数据插入+ 指定列插入`
        • `1.3 插入否则更新`
        • `1.4 替换`
      • `2 Retrieve`
        • `2.1 SELECT 列`
          • `2.1.1 全列查询`
          • `2.1.2 指定列查询`
          • `2.1.3 查询字段为表达式`
          • `2.1.4 为查询结果指定别名`
          • `2.1.5 结果去重`
        • `2.2 WHERE 条件`
          • `2.2.9 NULL 的查询`
        • `2.3 结果排序 `
          • 2.4 筛选分页结果
      • `3 Update`
      • `4 Delete`
        • `4.1 删除数据`
        • 4.2 截断表
        • `5 插入查询结果`
        • `6 聚合函数`
        • `6.7 group by子句的使用`


表的增删查改

  • CRUD : Create(创建), Retrieve(读取),Update(更新),Delete(删除)

1 Create

案例:

-- 创建一张学生表
mysql> create table student(-> id int unsigned primary key auto_increment,-> sn int not null unique key comment '学号',-> name varchar(20) not null comment '姓名',-> qq varchar(20) unique key-> );
Query OK, 0 rows affected (0.04 sec)mysql> desc student;
+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| id    | int unsigned | NO   | PRI | NULL    | auto_increment |
| sn    | int          | NO   | UNI | NULL    |                |
| name  | varchar(20)  | NO   |     | NULL    |                |
| qq    | varchar(20)  | YES  | UNI | NULL    |                |
+-------+--------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
Insert

语法:

--values就像一个扁担一样,左边是列属性,右边是对应的内容--insert [into] table_name (列属性,逗号分隔) values (对应前面列的待插入内容,逗号分隔) --指定列插入insert [into] table_name values (插入内容); --全插入
--其中插入的内容是严格与你表格的列属性顺序是一致的

1.1 单行数据 + 全列插入+指定列插入

-- 插入两条记录,value_list 数量必须和定义表的列的数量及顺序一致
-- 注意,这里在插入的时候,也可以不用指定id(当然,那时候就需要明确插入数据到那些列了),
那么mysql会使用默认的值进行自增。
mysql> insert into student values (1,001,'孙悟空',null);  --全插入
Query OK, 1 row affected (0.03 sec)mysql> insert into student (sn,name,qq) values (002,'唐三藏','12345'); --指定列插入
Query OK, 1 row affected (0.01 sec)   --没有插入id,id自增到2-- 查看插入结果
mysql> select * from student;
+----+----+-----------+-------+
| id | sn | name      | qq    |
+----+----+-----------+-------+
|  1 |  1 | 孙悟空    | NULL  |
|  2 |  2 | 唐三藏    | 12345 |
+----+----+-----------+-------+
2 rows in set (0.00 sec)
1.2 多行数据插入+ 指定列插入

-- 插入两条记录,value_list 数量必须和指定列数量及顺序一致mysql> insert into student (id,sn,name) values -> (100,101,'曹孟德'),-> (101,111,'孙仲谋');
Query OK, 2 rows affected (0.01 sec)
Records: 2  Duplicates: 0  Warnings: 0-- 查看插入结果
mysql> select * from student;
+-----+-----+-----------+-------+
| id  | sn  | name      | qq    |
+-----+-----+-----------+-------+
|   1 |   1 | 孙悟空    | NULL  |
|   2 |   2 | 唐三藏    | 12345 |
| 100 | 101 | 曹孟德    | NULL  |
| 101 | 111 | 孙仲谋    | NULL  |
+-----+-----+-----------+-------+
4 rows in set (0.00 sec)
1.3 插入否则更新

由于 主键 或者 唯一键 对应的值已经存在而导致插入失败

-- 主键冲突
mysql> insert into student (id,name,sn) values (101,'孙策','112');
ERROR 1062 (23000): Duplicate entry '101' for key 'student.PRIMARY'-- 唯一键冲突
mysql> insert into student (sn,name) values (111,'孙策');
ERROR 1062 (23000): Duplicate entry '111' for key 'student.sn'

可以选择性的进行同步更新操作语法:

INSERT ... ON DUPLICATE KEY UPDATE
column = value [, column = value] ...
mysql> insert into student (id,name,sn) values (101,'孙策','112')  -> on duplicate key updatee id=102,name='孙策',sn=112;
Query OK, 2 rows affected (0.01 sec)-- 0 row affected: 表中有冲突数据,但冲突数据的值和 update 的值相等
-- 1 row affected: 表中没有冲突数据,数据被插入
-- 2 row affected: 表中有冲突数据,并且数据已经被更新
-- 通过 MySQL 函数获取受到影响的数据行数
mysql> select row_count();
+-------------+
| ROW_COUNT() |
+-------------+
|           2 |
+-------------+
1 row in set (0.00 sec)
-- ON DUPLICATE KEY 当发生重复key的时候--插入成功
mysql> select * from student;
+-----+-----+-----------+-------+
| id  | sn  | name      | qq    |
+-----+-----+-----------+-------+
|   1 |   1 | 孙悟空    | NULL  |
|   2 |   2 | 唐三藏    | 12345 |
| 100 | 101 | 曹孟德    | NULL  |
| 102 | 112 | 孙策      | NULL  |
+-----+-----+-----------+-------+
4 rows in set (0.00 sec)

1.4 替换

语法:

replace into table_name ( 列属性 ) values(列内容)

案例:

mysql> select * from student;
+-----+-----+-----------+-------+
| id  | sn  | name      | qq    |
+-----+-----+-----------+-------+
|   1 |   1 | 孙悟空    | NULL  |
|   2 |   2 | 唐三藏    | 12345 |
| 100 | 101 | 曹孟德    | NULL  |
| 102 | 112 | 孙策      | NULL  |
+-----+-----+-----------+-------+
4 rows in set (0.00 sec)-- 主键 或者 唯一键 没有冲突,则直接插入;
-- 主键 或者 唯一键 如果冲突,则删除后再插入;mysql> replace into student (sn,name) values (101,'猪八戒');
Query OK, 2 rows affected (0.00 sec)
-- 1 row affected: 表中没有冲突数据,数据被插入
-- 2 row affected: 表中有冲突数据,删除后重新插入mysql> select * from student;
+-----+-----+-----------+-------+
| id  | sn  | name      | qq    |
+-----+-----+-----------+-------+
|   1 |   1 | 孙悟空    | NULL  |
|   2 |   2 | 唐三藏    | 12345 |
| 102 | 112 | 孙策      | NULL  |
| 103 | 101 | 猪八戒    | NULL  |
+-----+-----+-----------+-------+
4 rows in set (0.00 sec)


2 Retrieve

准备测试表结构与数据

-- 创建表结构
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.03 sec)-- 插入测试数据
mysql> insert into exam_result (name,chinese,math,english) values-> ('刘备',67,98,56),-> ('孙权',87,78,77),-> ('曹超',88,98,90),-> ('诸葛亮',82,84,67),-> ('关羽',55,85,47),-> ('小乔',70,73,78),-> ('貂蝉',75,65,30)-> ;
Query OK, 7 rows affected (0.00 sec)
Records: 7  Duplicates: 0  Warnings: 0
2.1 SELECT 列
2.1.1 全列查询
-- 通常情况下不建议使用 * 进行全列查询
-- 1. 查询的列越多,意味着需要传输的数据量越大;
-- 2. 可能会影响到索引的使用。
mysql> select * from exam_result;
+----+-----------+---------+------+---------+
| id | name      | chinese | math | english |
+----+-----------+---------+------+---------+
|  1 | 刘备      |      67 |   98 |      56 |
|  2 | 孙权      |      87 |   78 |      77 |
|  3 | 曹超      |      88 |   98 |      90 |
|  4 | 诸葛亮    |      82 |   84 |      67 |
|  5 | 关羽      |      55 |   85 |      47 |
|  6 | 小乔      |      70 |   73 |      78 |
|  7 | 貂蝉      |      75 |   65 |      30 |
+----+-----------+---------+------+---------+
7 rows in set (0.00 sec)
2.1.2 指定列查询

-- 指定列的顺序不需要按定义表的顺序来
mysql> select name,chinese from exam_result;
+-----------+---------+
| name      | chinese |
+-----------+---------+
| 刘备      |      67 |
| 孙权      |      87 |
| 曹超      |      88 |
| 诸葛亮    |      82 |
| 关羽      |      55 |
| 小乔      |      70 |
| 貂蝉      |      75 |
+-----------+---------+
7 rows in set (0.00 sec)
2.1.3 查询字段为表达式
-- 表达式不包含字段
mysql> select id,name,chinese+10 from exam_result;
+----+-----------+------------+
| id | name      | chinese+10 |
+----+-----------+------------+
|  1 | 刘备      |         77 |
|  2 | 孙权      |         97 |
|  3 | 曹超      |         98 |
|  4 | 诸葛亮    |         92 |
|  5 | 关羽      |         65 |
|  6 | 小乔      |         80 |
|  7 | 貂蝉      |         85 |
+----+-----------+------------+
7 rows in set (0.00 sec)

-- 表达式包含多个字段
mysql> select id,name,chinese+math+english from exam_result;
+----+-----------+----------------------+
| id | name      | chinese+math+english |
+----+-----------+----------------------+
|  1 | 刘备      |                  221 |
|  2 | 孙权      |                  242 |
|  3 | 曹超      |                  276 |
|  4 | 诸葛亮    |                  233 |
|  5 | 关羽      |                  187 |
|  6 | 小乔      |                  221 |
|  7 | 貂蝉      |                  170 |
+----+-----------+----------------------+
7 rows in set (0.00 sec)
2.1.4 为查询结果指定别名

语法:

mysql> select id,name,chinese+math+english as total from exam_result;
+----+-----------+-------+
| id | name      | total |
+----+-----------+-------+
|  1 | 刘备      |   221 |
|  2 | 孙权      |   242 |
|  3 | 曹超      |   276 |
|  4 | 诸葛亮    |   233 |
|  5 | 关羽      |   187 |
|  6 | 小乔      |   221 |
|  7 | 貂蝉      |   170 |
+----+-----------+-------+
7 rows in set (0.00 sec)--as可以省略
mysql> select id,name,chinese+math+english total from exam_result;
+----+-----------+-------+
| id | name      | total |
+----+-----------+-------+
|  1 | 刘备      |   221 |
|  2 | 孙权      |   242 |
|  3 | 曹超      |   276 |
|  4 | 诸葛亮    |   233 |
|  5 | 关羽      |   187 |
|  6 | 小乔      |   221 |
|  7 | 貂蝉      |   170 |
+----+-----------+-------+
7 rows in set (0.00 sec)

2.1.5 结果去重
-- 98 分重复了
mysql> select math from exam_result;
+------+
| math |
+------+
|   98 |
|   78 |
|   98 |
|   84 |
|   85 |
|   73 |
|   65 |
+------+
7 rows in set (0.00 sec)
-- 去重结果
mysql> select distinct math from exam_result;
+------+
| math |
+------+
|   98 |
|   78 |
|   84 |
|   85 |
|   73 |
|   65 |
+------+
6 rows in set (0.00 sec)
2.2 WHERE 条件

比较运算符:

逻辑运算符:

2.2.1 英语不及格的同学及英语成绩 ( < 60 )

-- 基本比较
mysql> select name,chinese from exam_result where chinese<60;
+--------+---------+
| name   | chinese |
+--------+---------+
| 关羽   |      55 |
+--------+---------+
1 row in set (0.00 sec)

2.2.2 语文成绩在 [80, 90] 分的同学及语文成绩

-- 使用 and 进行条件连接
mysql> select id,name,chinese from exam_result where chinese>60 and chinese<90;
+----+-----------+---------+
| id | name      | chinese |
+----+-----------+---------+
|  1 | 刘备      |      67 |
|  2 | 孙权      |      87 |
|  3 | 曹超      |      88 |
|  4 | 诸葛亮    |      82 |
|  6 | 小乔      |      70 |
|  7 | 貂蝉      |      75 |
+----+-----------+---------+
6 rows in set (0.00 sec)
-- 使用 BETWEEN ... and ... 条件
mysql> select id,name,chinese from exam_result where chinese between 60 and 90;
+----+-----------+---------+
| id | name      | chinese |
+----+-----------+---------+
|  1 | 刘备      |      67 |
|  2 | 孙权      |      87 |
|  3 | 曹超      |      88 |
|  4 | 诸葛亮    |      82 |
|  6 | 小乔      |      70 |
|  7 | 貂蝉      |      75 |
+----+-----------+---------+
6 rows in set (0.00 sec) 

2.2.3 数学成绩是 58 或者 59 或者 98 或者 99 分的同学及数学成绩

-- 使用 OR 进行条件连接
mysql> select id,name,math from exam_result -> where math=58 or -> math=59 or -> math=98 or -> math=99;
+----+--------+------+
| id | name   | math |
+----+--------+------+
|  1 | 刘备   |   98 |
|  3 | 曹超   |   98 |
+----+--------+------+
2 rows in set (0.00 sec)
-- 使用 IN 条件
mysql> select id,name,math from exam_result -> where math in (58,59,98,99);
+----+--------+------+
| id | name   | math |
+----+--------+------+
|  1 | 刘备   |   98 |
|  3 | 曹超   |   98 |
+----+--------+------+
2 rows in set (0.00 sec)

2.2.4 姓孙的同学 及 孙某同学

-- % 匹配任意多个(包括 0 个)任意字符
mysql> select id,name from exam_result where name like '孙%';
+----+-----------+
| id | name      |
+----+-----------+
|  2 | 孙权      |
|  8 | 孙悟空    |
+----+-----------+
2 rows in set (0.00 sec)
-- _ 匹配严格的一个任意字符
mysql> select id,name from exam_result where name like '孙_';
+----+--------+
| id | name   |
+----+--------+
|  2 | 孙权   |
+----+--------+
1 row in set (0.00 sec)

2.2.5 语文成绩好于英语成绩的同学

-- WHERE 条件中比较运算符两侧都是字段
mysql> select name,chinese,english from exam_result where chinese>english;
+-----------+---------+---------+
| name      | chinese | english |
+-----------+---------+---------+
| 刘备      |      67 |      56 |
| 孙权      |      87 |      77 |
| 诸葛亮    |      82 |      67 |
| 关羽      |      55 |      47 |
| 貂蝉      |      75 |      30 |
| 孙悟空    |      99 |      77 |
+-----------+---------+---------+
6 rows in set (0.00 sec)

2.2.6 总分在 200 分以下的同学

-- WHERE 条件中使用表达式
-- 别名不能用在 WHERE 条件中
mysql> select name,chinese+math+english total from exam_result where chinese+math+english>200;
+-----------+-------+
| name      | total |
+-----------+-------+
| 刘备      |   221 |
| 孙权      |   242 |
| 曹超      |   276 |
| 诸葛亮    |   233 |
| 小乔      |   221 |
| 孙悟空    |   264 |
+-----------+-------+
6 rows in set (0.01 sec)-- 别名不能用在 WHERE 条件中
mysql> select name,chinese+math+english total from exam_result where total>200;
ERROR 1054 (42S22): Unknown column 'total' in 'where clause'

2.2.7 语文成绩 > 80 并且不姓孙的同学

-- AND 与 NOT 的使用
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.2.8 孙某同学,否则要求总成绩 > 200 并且 语文成绩 < 数学成绩 并且 英语成绩 > 80

-- 综合性查询
mysql> select name,chinese,math,english,chinese+math+english total -> from exam_result  where -> name like '孙_' or -> (chinese+math+english>200 and chinese<math and english>80);
+--------+---------+------+---------+-------+
| name   | chinese | math | english | total |
+--------+---------+------+---------+-------+
| 孙权   |      87 |   78 |      77 |   242 |
| 曹超   |      88 |   98 |      90 |   276 |
+--------+---------+------+---------+-------+
2 rows in set (0.00 sec)
2.2.9 NULL 的查询

-- 查询 students 表
mysql> select * from student;
+-----+-----+-----------+-------+
| id  | sn  | name      | qq    |
+-----+-----+-----------+-------+
|   1 |   1 | 孙悟空    | NULL  |
|   2 |   2 | 唐三藏    | 12345 |
| 102 | 112 | 孙策      | NULL  |
| 103 | 101 | 猪八戒    | NULL  |
+-----+-----+-----------+-------+
4 rows in set (0.00 sec)-- 查询 qq 号已知的同学姓名
mysql> select name,qq from student where qq is not null;
+-----------+-------+
| name      | qq    |
+-----------+-------+
| 唐三藏    | 12345 |
+-----------+-------+
1 row in set (0.00 sec)-- NULL 和 NULL 的比较,=<=> 的区别
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.00 sec)
2.3 结果排序

语法:

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

注意:没有 ORDER BY 子句的查询,返回的顺序是未定义的,永远不要依赖这个顺序

案例:

2.3.1 同学及数学成绩,按数学成绩升序显示

mysql> select name,math from exam_result order by math asc;
+-----------+------+
| name      | math |
+-----------+------+
| 貂蝉      |   65 |
| 小乔      |   73 |
| 孙权      |   78 |
| 诸葛亮    |   84 |
| 关羽      |   85 |
| 孙悟空    |   88 |
| 刘备      |   98 |
| 曹超      |   98 |
+-----------+------+
8 rows in set (0.00 sec)

2.3.2 同学及 qq 号,按 qq 号排序显示

-- NULL 视为比任何值都小,升序出现在最上面
mysql> select name,qq from student order by qq;
+-----------+-------+
| name      | qq    |
+-----------+-------+
| 孙悟空    | NULL  |
| 孙策      | NULL  |
| 猪八戒    | NULL  |
| 唐三藏    | 12345 |
+-----------+-------+
4 rows in set (0.00 sec)

2.3.3 查询同学各门成绩,依次按 数学降序,英语升序,语文升序的方式显示

-- 多字段排序,排序优先级随书写顺序
mysql> select name,math,english,chinese from exam_result -> order by math desc,-> english asc, -> chinese asc;
+-----------+------+---------+---------+
| name      | math | english | chinese |
+-----------+------+---------+---------+
| 刘备      |   98 |      56 |      67 |
| 曹超      |   98 |      90 |      88 |
| 孙悟空    |   88 |      77 |      99 |
| 关羽      |   85 |      47 |      55 |
| 诸葛亮    |   84 |      67 |      82 |
| 孙权      |   78 |      77 |      87 |
| 小乔      |   73 |      78 |      70 |
| 貂蝉      |   65 |      30 |      75 |
+-----------+------+---------+---------+
8 rows in set (0.00 sec)

2.3.4 查询同学及总分,由高到低

-- ORDER BY 中可以使用表达式
mysql> select name,chinese+math+english total from exam_result -> order by chinese+math+english desc;
+-----------+-------+
| name      | total |
+-----------+-------+
| 曹超      |   276 |
| 孙悟空    |   264 |
| 孙权      |   242 |
| 诸葛亮    |   233 |
| 刘备      |   221 |
| 小乔      |   221 |
| 关羽      |   187 |
| 貂蝉      |   170 |
+-----------+-------+
8 rows in set (0.00 sec)-- ORDER BY 子句中可以使用列别名
mysql> select name,chinese+math+english total from exam_result -> order by total desc;
+-----------+-------+
| name      | total |
+-----------+-------+
| 曹超      |   276 |
| 孙悟空    |   264 |
| 孙权      |   242 |
| 诸葛亮    |   233 |
| 刘备      |   221 |
| 小乔      |   221 |
| 关羽      |   187 |
| 貂蝉      |   170 |
+-----------+-------+
8 rows in set (0.00 sec)-- 执行顺序
FROM 子句:访问 exam_result 表,获取所有行。
计算 SELECT 子句中的表达式:对每一行,计算 chinese + math + english 的值,并将其命名为 total。
ORDER BY 子句:根据 total 的值对结果进行降序排序。
返回结果:返回排序后的结果集,包括 name 和计算得到的 total。
--注意事项
别名使用:在 SELECT 子句中定义的别名(如 total)可以在 ORDER BY 子句中使用,
因为 ORDER BY 是在 SELECT 之后处理的(在逻辑上,尽管优化器可能会调整实际执行顺序)。

2.3.5 查询姓孙的同学或者姓曹的同学数学成绩,结果按数学成绩由高到低显示

-- 结合 WHERE 子句 和 ORDER BY 子句
mysql> select name,math from exam_result -> where (name like '孙%' or name like '曹%') -> order by math desc;
+-----------+------+
| name      | math |
+-----------+------+
| 曹超      |   98 |
| 孙悟空    |   88 |
| 孙权      |   78 |
+-----------+------+
3 rows in set (0.00 sec)
2.4 筛选分页结果

语法:

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

建议:对未知表进行查询时,最好加一条 LIMIT 1,避免因为表中数据过大,查询全表数据导致数据库卡死

按 id 进行分页,每页 3 条记录,分别显示 第 1、2、3 页

-- 第 1 页
mysql> select name,chinese from exam_result limit 0,3;
+--------+---------+
| name   | chinese |
+--------+---------+
| 刘备   |      67 |
| 孙权   |      87 |
| 曹超   |      88 |
+--------+---------+
3 rows in set (0.00 sec)
mysql> select name,chinese from exam_result limit 3,3;
+-----------+---------+
| name      | chinese |
+-----------+---------+
| 诸葛亮    |      82 |
| 关羽      |      55 |
| 小乔      |      70 |
+-----------+---------+
3 rows in set (0.00 sec)mysql> select name,chinese from exam_result limit 3 offset 3;
+-----------+---------+
| name      | chinese |
+-----------+---------+
| 诸葛亮    |      82 |
| 关羽      |      55 |
| 小乔      |      70 |
+-----------+---------+
3 rows in set (0.00 sec)
-- 第 3 页,如果结果不足 3 个,不会有影响
mysql> select name,chinese from exam_result limit 6,3;
+-----------+---------+
| name      | chinese |
+-----------+---------+
| 貂蝉      |      75 |
| 孙悟空    |      99 |
+-----------+---------+
2 rows in set (0.00 sec)mysql> select name,chinese from exam_result limit 3 offset 6;
+-----------+---------+
| name      | chinese |
+-----------+---------+
| 貂蝉      |      75 |
| 孙悟空    |      99 |
+-----------+---------+
2 rows in set (0.00 sec)


3 Update

语法:

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

对查询到的结果进行列值更新

案例:

3.1 将孙悟空同学的数学成绩变更为 80 分

-- 更新值为具体值
-- 查看原数据
mysql> update exam_result set math=80 where name='孙悟空';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0mysql> select name,math from exam_result where name='孙悟空';
+-----------+------+
| name      | math |
+-----------+------+
| 孙悟空    |   80 |
+-----------+------+
1 row in set (0.00 sec)

3.2 将貂蝉同学的数学成绩变更为 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: 0mysql> select name,chinese,math from exam_result where name='貂蝉';
+--------+---------+------+
| name   | chinese | math |
+--------+---------+------+
| 貂蝉   |      70 |   60 |
+--------+---------+------+
1 row in set (0.00 sec)

3.3 将总成绩倒数前三的 3 位同学的数学成绩加上 30 分

-- 更新值为原值基础上变更
-- 查看原数据
-- 别名可以在ORDER BY中使用
mysql> select name,chinese+math+english total -> from exam_result order by total asc limit 0,3;
+--------+-------+
| name   | total |
+--------+-------+
| 貂蝉   |   160 |
| 关羽   |   187 |
| 小乔   |   221 |
+--------+-------+
3 rows in set (0.00 sec)-- 数据更新,不支持 math += 30 这种语法
mysql> update exam_result set math = math + 30 -> order by chinese+math+english asc limit 3;
Query OK, 3 rows affected (0.00 sec)
Rows matched: 3  Changed: 3  Warnings: 0--注意:
在 UPDATE 语句中使用 LIMIT 时,MySQL不支持 LIMIT offset, row_count 这种带有偏移量的完整形式;
它只支持 LIMIT row_count。这是因为 UPDATE 语句的目的是修改数据,而不是像 SELECT 语句那样检索数据,
所以通常不需要跳过一定数量的行再开始更新。mysql> update exam_result set math = math + 30 -> order by chinese+math+english asc limit 0,3;
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 ',3' at line 1

3.4 将所有同学的语文成绩更新为原来的 2 倍

注意:更新全表的语句慎用

-- 没有 WHERE 子句,则更新全表
-- 查看原数据
mysql> select * from exam_result;
+----+-----------+---------+------+---------+
| id | name      | chinese | math | english |
+----+-----------+---------+------+---------+
|  1 | 刘备      |      67 |  128 |      56 |
|  2 | 孙权      |      87 |   48 |      77 |
|  3 | 曹超      |      88 |   98 |      90 |
|  4 | 诸葛亮    |      82 |   54 |      67 |
|  5 | 关羽      |      55 |  145 |      47 |
|  6 | 小乔      |      70 |  103 |      78 |
|  7 | 貂蝉      |      70 |   90 |      30 |
|  8 | 孙悟空    |      99 |   80 |      77 |
+----+-----------+---------+------+---------+
8 rows in set (0.00 sec)//更新数据
mysql> update exam_result set chinese=chinese*2;
Query OK, 8 rows affected (0.01 sec)
Rows matched: 8  Changed: 8  Warnings: 0//查看更新后的数据
mysql> select * from exam_result;
+----+-----------+---------+------+---------+
| id | name      | chinese | math | english |
+----+-----------+---------+------+---------+
|  1 | 刘备      |     134 |  128 |      56 |
|  2 | 孙权      |     174 |   48 |      77 |
|  3 | 曹超      |     176 |   98 |      90 |
|  4 | 诸葛亮    |     164 |   54 |      67 |
|  5 | 关羽      |     110 |  145 |      47 |
|  6 | 小乔      |     140 |  103 |      78 |
|  7 | 貂蝉      |     140 |   90 |      30 |
|  8 | 孙悟空    |     198 |   80 |      77 |
+----+-----------+---------+------+---------+
8 rows in set (0.00 sec)


4 Delete

4.1 删除数据

语法:

delete from table_name [WHERE ...] [ORDER BY ...] [LIMIT ...]

案例:

4.1.1 删除孙悟空同学的考试成绩

-- 查看原数据
mysql> select * from exam_result;
+----+-----------+---------+------+---------+
| id | name      | chinese | math | english |
+----+-----------+---------+------+---------+
|  1 | 刘备      |     134 |  128 |      56 |
|  2 | 孙权      |     174 |   48 |      77 |
|  3 | 曹超      |     176 |   98 |      90 |
|  4 | 诸葛亮    |     164 |   54 |      67 |
|  5 | 关羽      |     110 |  145 |      47 |
|  6 | 小乔      |     140 |  103 |      78 |
|  7 | 貂蝉      |     140 |   90 |      30 |
|  8 | 孙悟空    |     198 |   80 |      77 |
+----+-----------+---------+------+---------+
8 rows in set (0.00 sec)-- 删除数据
mysql> delete from exam_result where name='孙悟空';
Query OK, 1 row affected (0.01 sec)-- 查看删除结果
mysql> select * from exam_result;
+----+-----------+---------+------+---------+
| id | name      | chinese | math | english |
+----+-----------+---------+------+---------+
|  1 | 刘备      |     134 |  128 |      56 |
|  2 | 孙权      |     174 |   48 |      77 |
|  3 | 曹超      |     176 |   98 |      90 |
|  4 | 诸葛亮    |     164 |   54 |      67 |
|  5 | 关羽      |     110 |  145 |      47 |
|  6 | 小乔      |     140 |  103 |      78 |
|  7 | 貂蝉      |     140 |   90 |      30 |
+----+-----------+---------+------+---------+
7 rows in set (0.00 sec)

4.1.2 删除整张表数据

注意:删除整表操作要慎用

-- 准备测试表
create table for_delete (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(20)
);
Query OK, 0 rows affected (0.16 sec)-- 插入测试数据
insert into for_delete (name) VALUES ('A'), ('B'), ('C');
Query OK, 3 rows affected (1.05 sec)
Records: 3 Duplicates: 0 Warnings: 0-- 查看测试数据
select * from for_delete;
+----+------+
| id | name |
+----+------+
| 1  |   A  |
| 2  |   B  |
| 3  |   C  |
+----+------+
3 rows in set (0.00 sec)

-- 删除整表数据--注意:是删除整张表的数据,表的结构没有被删除
delete from for_delete;
Query OK, 3 rows affected (0.00 sec)-- 查看删除结果
SELECT * FROM for_delete;
Empty set (0.00 sec)
-- 再插入一条数据,自增 id 在原值上增长
insert into for_delete (name) VALUES ('D');
Query OK, 1 row affected (0.00 sec)-- 查看数据
select * from for_delete;
+----+------+
| id | name |
+----+------+
| 4  |   D  |
+----+------+
1 row in set (0.00 sec)-- 查看表结构,会有 AUTO_INCREMENT=n 项
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=5 DEFAULT CHARSET=utf8
1 row in set (0.00 sec)
4.2 截断表

语法:

truncate [table] table_name

注意:这个操作慎用

1. 只能对整表操作,不能像 DELETE 一样针对部分数据操作;

2. 实际上 truncate不对数据操作,所以比 DELETE 更快,但是 truncate在删除数据的时候,并不经过真正的事物,所以无法回滚

3. 会重置 AUTO_INCREMENT 项

-- 准备测试表
mysql> create table for_truncate( -> id int primary key auto_increment,-> name varchar(20) );
Query OK, 0 rows affected (0.04 sec)mysql> insert into for_truncate (name) values ('A'),('B'),('C');
Query OK, 3 rows affected (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 0mysql> select * from for_truncate;
+----+------+
| id | name |
+----+------+
|  1 | A    |
|  2 | B    |
|  3 | C    |
+----+------+
3 rows in set (0.00 sec)
-- 截断整表数据,注意影响行数是 0,所以实际上没有对数据真正操作
mysql> truncate for_truncate;
Query OK, 0 rows affected (0.04 sec)-- 查看删除结果
mysql> select * from for_truncate;
Empty set (0.00 sec)
-- 再插入一条数据,自增 id 在重新增长
mysql> insert into for_truncate (name) values ('D');
Query OK, 1 row affected (0.01 sec)mysql> select * from for_truncate;
+----+------+
| id | name |
+----+------+
|  1 | D    |
+----+------+
1 row in set (0.00 sec)-- 查看表结构,会有 AUTO_INCREMENT=2 项
mysql> show create table for_truncate\G
*************************** 1. row ***************************Table: for_truncate
Create Table: CREATE TABLE `for_truncate` (`id` int NOT NULL AUTO_INCREMENT,`name` varchar(20) DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
1 row in set (0.00 sec)
5 插入查询结果

语法:

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

案例:删除表中的的重复复记录,重复的数据只能有一份

-- 创建原数据表
mysql> create table duplicate_table (id int, name varchar(20));
Query OK, 0 rows affected (0.01 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.00 sec)
Records: 6 Duplicates: 0 Warnings: 0

思路:

-- 创建一张空表 no_duplicate_table,结构和 duplicate_table 一样
create table no_duplicate_table LIKE duplicate_table;
Query OK, 0 rows affected (0.00 sec)
-- 将 duplicate_table 的去重数据插入到 no_duplicate_table
insert into no_duplicate_table select distinct * from duplicate_table;
Query OK, 3 rows affected (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 0
-- 通过重命名表,实现原子的去重操作
rename table duplicate_table to old_duplicate_table,
no_duplicate_table TO duplicate_table;
Query OK, 0 rows affected (0.00 sec)
-- 查看最终结果
select * from duplicate_table;
+------+------+
| id | name |
+------+------+
| 100 | aaa |
| 200 | bbb |
| 300 | ccc |
+------+------+
3 rows in set (0.00 sec)


6 聚合函数

函数说明
COUNT([DISTINCT] expr)返回查询到的数据的 数量
SUM([DISTINCT] expr)返回查询到的数据的 总和,不是数字没有意义
AVG([DISTINCT] expr)返回查询到的数据的 平均值,不是数字没有意义
MAX([DISTINCT] expr)返回查询到的数据的 最大值,不是数字没有意义
MIN([DISTINCT] expr)返回查询到的数据的 最小值,不是数字没有意义

案例:

6.1 统计班级共有多少同学

-- 使用 * 做统计,不受 NULL 影响
select count(*) from students;
+----------+
| count(*) |
+----------+
|				 4 |
+----------+
1 row in set (0.00 sec)
-- 使用表达式做统计
select count(1) from students;
+----------+
| COUNT(1) |
+----------+
| 			 4 |
+----------+
1 row in set (0.00 sec)

6.2 统计班级收集的 qq 号有多少

-- NULL 不会计入结果
select cout(qq) FROM students;
+-----------+
| count(qq) |
+-----------+
|         1 |
+-----------+
1 row in set (0.00 sec)

6.3 统计本次考试的数学成绩分数个数

-- COUNT(math) 统计的是全部成绩
select count(math) from exam_result;
+---------------+
|	  count(math) |
+---------------+
| 						6 |
+---------------+
1 row in set (0.00 sec)
-- count(distinct math) 统计的是去重成绩数量
select count(distinct math) FROM exam_result;
+------------------------+
|   count(distinct math) |
+------------------------+
| 										 5 |
+------------------------+
1 row in set (0.00 sec)

6.4 统计数学成绩总分

SELECT SUM(math) FROM exam_result;
+-------------+
|   SUM(math) |
+-------------+
|         569 |
+-------------+
1 row in set (0.00 sec)
-- 不及格 < 60 的总分,没有结果,返回 NULL
SELECT SUM(math) FROM exam_result WHERE math < 60;
+-------------+
|   SUM(math) |
+-------------+
|        NULL |
+-------------+
1 row in set (0.00 sec)

6.4 统计平均总分

SELECT AVG(chinese + math + english) 平均总分 FROM exam_result;
+--------------+
|     平均总分 |
+--------------+
|        297.5 |
+--------------+

6.5 返回英语最高分

SELECT MAX(english) FROM exam_result;
+-------------+
| MAX(english)|
+-------------+
|          90 |
+-------------+
1 row in set (0.00 sec)

6.6 返回 > 70 分以上的数学最低分

SELECT MIN(math) FROM exam_result WHERE math > 70;
+-------------+
|   MIN(math) |
+-------------+
|          73 |
+-------------+
1 row in set (0.00 sec)


6.7 group by子句的使用

在select中使用group by 子句可以对指定列进行分组查询

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

如何显示每个部门的平均工资和最高工资

select deptno,avg(sal),max(sal) from EMP group by deptno; 

显示每个部门的每种岗位的平均工资和最低工资

select avg(sal),min(sal),job, deptno from EMP group by deptno, job; 

显示平均工资低于2000的部门和它的平均工资

  • 统计各个部门的平均工资
select avg(sal) from EMP group by deptno 

having和group by配合使用,对group by结果进行过滤

select avg(sal) as myavg from EMP group by deptno having myavg<2000;
--having经常和group by搭配使用,作用是对分组进行筛选,作用有些像where。
  • 在 MySQL 中,HAVING 子句通常与 GROUP BY 子句一起使用,用于对分组后的结果进行过滤。与 WHERE 子句不同,WHERE 是在分组前对数据进行过滤,而 HAVING 是在分组和聚合计算后对数据进行过滤。
  • 顺序:HAVING 子句在 GROUP BY 子句之后执行,因此它只能引用在 SELECT 列表或 GROUP BY 子句中定义的聚合函数或分组列。

相关文章:

  • Kafka消费者端重平衡流程
  • 《软件设计师》复习笔记(14.2)——统一建模语言UML、事务关系图
  • 遨游科普:三防平板除了三防特性?还能实现什么功能?
  • 工业触摸显示器助力智慧工业实验室发展
  • OpenStack Yoga版安装笔记(22)Swift笔记20250418
  • vue3 Element-plus修改内置样式复现代码
  • (7)VTK C++开发示例 --- 使用交互器
  • Java 2025:解锁未来5大技术趋势,Kotlin融合AI新篇
  • 【dify实战】agent结合deepseek实现基于自然语言的数据库问答、Echarts可视化展示、Excel报表下载
  • 什么是线程安全
  • 软件详细设计说明书模板
  • 《Learning Langchain》阅读笔记3-基于 Gemini 的 Langchain如何从LLMs中获取特定格式
  • 【Mamba】MambaVision论文阅读
  • MCP(Model Context Protocol 模型上下文协议)科普
  • 【数据融合实战手册·实战篇】二维赋能三维的5种高阶玩法:手把手教你用Mapmost打造智慧城市标杆案例
  • STM32F407的引脚说明
  • C++ `shared_ptr` 多线程使用
  • OrangePi 5 Pro vs OrangePi AI Pro 详细对比分析
  • 基于CNN与VGG16的图像识别快速实现指南
  • spring:加载配置类
  • 人民文学奖颁出,董宇辉获传播贡献奖
  • 在没有穹顶的剧院,和春天的音乐会来一场约会
  • 希音、Temu告知美国消费者4月25日起涨价:关税变化导致运营成本上升
  • 谁在地铁里阅读?——对话上海地铁上的读书人
  • 日本央行行长:美关税政策将冲击日本经济
  • 欧洲央行再次宣布降息:三大关键利率分别下调25个基点