MySQL表的增删改查

1. insert

bash 复制代码
INSERT [INTO] table_name 
 [(column [, column] ...)] 
 VALUES (value_list) [, (value_list)] ...
 
value_list: value, [, value] ...

案例:

bash 复制代码
-- 创建一张学生表
CREATE TABLE students (
   id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
   sn INT NOT NULL UNIQUE COMMENT '学号',
   name VARCHAR(20) NOT NULL,
   qq VARCHAR(20)
);

单行数据 + 全列插入

bash 复制代码
INSERT INTO students VALUES (100, 10000, '唐三藏', NULL);
Query OK, 1 row affected (0.02 sec)
INSERT INTO students VALUES (101, 10001, '孙悟空', '11111');
Query OK, 1 row affected (0.02 sec)
-- 查看插入结果
SELECT * FROM students;
+-----+-------+-----------+-------+
| id | sn   | name     | qq   |
+-----+-------+-----------+-------+
| 100 | 10000 | 唐三藏     | NULL |
| 101 | 10001 | 孙悟空     | 11111 |
+-----+-------+-----------+-------+

多行数据 + 指定列插入

bash 复制代码
INSERT INTO students (id, sn, name) VALUES 
 (102, 20001, '曹孟德'), 
 (103, 20002, '孙仲谋');
Query OK, 2 rows affected (0.02 sec)
Records: 2 Duplicates: 0  Warnings: 0
-- 查看插入结果
SELECT * FROM students;
+-----+-------+-----------+-------+
| id | sn   | name     | qq   |
+-----+-------+-----------+-------+
| 100 | 10000 | 唐三藏     | NULL |
| 101 | 10001 | 孙悟空     | 11111 |
| 102 | 20001 | 曹孟德     | NULL |
| 103 | 20002 | 孙仲谋     | NULL |
+-----+-------+-----------+-------+

插入否则更新

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

bash 复制代码
-- 主键冲突
INSERT INTO students (id, sn, name) VALUES (100, 10010, '唐大师');
ERROR 1062 (23000): Duplicate entry '100' for key 'PRIMARY'
-- 唯一键冲突
INSERT INTO students (sn, name) VALUES (20001, '曹阿瞒');
ERROR 1062 (23000): Duplicate entry '20001' for key 'sn'

可以选择性的进行同步更新操作语法:
insert ... on duplicate key update 
 column = value [, column = value] ... 
bash 复制代码
INSERT INTO students (id, sn, name) VALUES (100, 10010, '唐大师')
 ON DUPLICATE KEY UPDATE sn = 10010, name = '唐大师';
Query OK, 2 rows affected (0.47 sec)

-- 0 row affected: 表中有冲突数据,但冲突数据的值和 update 的值相等
-- 1 row affected: 表中没有冲突数据,数据被插入
-- 2 row affected: 表中有冲突数据,并且数据已经被更新
-- 通过 MySQL 函数获取受到影响的数据行数

SELECT ROW_COUNT();
+-------------+
| ROW_COUNT() |
+-------------+
|           2 |
+-------------+
1 row in set (0.00 sec)
-- ON DUPLICATE KEY 当发生重复key的时候

替换

bash 复制代码
-- 主键 或者 唯一键 没有冲突,则直接插入;
-- 主键 或者 唯一键 如果冲突,则删除后再插入

REPLACE INTO students (sn, name) VALUES (20001, '曹阿瞒');
Query OK, 2 rows affected (0.00 sec)

-- 1 row affected: 表中没有冲突数据,数据被插入
-- 2 row affected: 表中有冲突数据,删除后重新插入

2. select语句

语法:

bash 复制代码
SELECT 
 [DISTINCT] {* | {column [, column] ...} -- 选择列(*表示所有列,AS可指定别名)
 [FROM table_name] -- 指定数据表
 [WHERE ...] -- 可选,行筛选条件
 [ORDER BY column [ASC | DESC], ...] -- 可选,排序(ASC升序,DESC降序,默认ASC)
 LIMIT [offset,] row_count  -- v限制返回行数(offset是偏移量,从0开始)

 SELECT name, score AS 成绩 
FROM student 
WHERE age >= 18 AND gender = '男'  -- 筛选18岁及以上的男生
ORDER BY score DESC  -- 按成绩降序排序
LIMIT 2;  -- 只返回前2行

全列查询

bash 复制代码
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.02 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, 45), 
    ->  ('孙权', 70, 73, 78), 
    ->  ('宋公明', 75, 65, 30);
Query OK, 7 rows affected (0.00 sec)
Records: 7  Duplicates: 0  Warnings: 0

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 |      45 |
|  6 | 孙权      |      70 |   73 |      78 |
|  7 | 宋公明    |      75 |   65 |      30 |
+----+-----------+---------+------+---------+
7 rows in set (0.00 sec)

指定列查询

bash 复制代码
mysql> select id,name,english from exam_result;
+----+-----------+---------+
| id | name      | english |
+----+-----------+---------+
|  1 | 唐三藏    |      56 |
|  2 | 孙悟空    |      77 |
|  3 | 猪悟能    |      90 |
|  4 | 曹孟德    |      67 |
|  5 | 刘玄德    |      45 |
|  6 | 孙权      |      78 |
|  7 | 宋公明    |      30 |
+----+-----------+---------+
7 rows in set (0.00 sec)

查询字段为表达式

bash 复制代码
-- 表达式包含一个字段
SELECT id, name, english + 10 FROM exam_result; 
+----+-----------+-------------+ 
| id | name | english + 10 | 
+----+-----------+-------------+ 
| 1 | 唐三藏 | 66              | 
| 2 | 孙悟空 | 87              | 
| 3 | 猪悟能 | 100             | 
| 4 | 曹孟德 | 77              | 
| 5 | 刘玄德 | 55              | 
| 6 | 孙权   | 88              | 
| 7 | 宋公明 | 40              | 
+----+-----------+-------------+ 
7 rows in set (0.00 sec)

-- 表达式包含多个字段 
 
SELECT id, name, chinese + math + english FROM exam_result; 
+----+-----------+-------------------------+ 
| id | name | chinese + math + english | 
+----+-----------+-------------------------+ 
| 1 | 唐三藏 | 221                          | 
| 2 | 孙悟空 | 242                          | 
| 3 | 猪悟能 | 276                          | 
| 4 | 曹孟德 | 233                          | 
| 5 | 刘玄德 | 185                          | 
| 6 | 孙权 | 221                            | 
| 7 | 宋公明 | 170                          | 
+----+-----------+-------------------------+ 

为查询结果指定别名(as

bash 复制代码
SELECT column [AS] alias_name [...] FROM table_name; 

mysql> SELECT id, name, chinese + math + english 总分 FROM exam_result;
+----+-----------+--------+
| id | name      | 总分   |
+----+-----------+--------+
|  1 | 唐三藏    |    221 |
|  2 | 孙悟空    |    242 |
|  3 | 猪悟能    |    276 |
|  4 | 曹孟德    |    233 |
|  5 | 刘玄德    |    185 |
|  6 | 孙权      |    221 |
|  7 | 宋公明    |    170 |
+----+-----------+--------+
7 rows in set (0.00 sec)

结果去重

bash 复制代码
mysql> select math from exam_result;
+------+
| math |
+------+
|   98 |--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)

3.where语句

比较运算符

运算符 说明
>, >=, <, <= 大于,大于等于,小于,小于等于
= 等于,NULL 不安全,例如 NULL = NULL 的结果是 NULL
<=> 等于,NULL 安全,例如 NULL <=> NULL 的结果是 TRUE(1)
!=, <> 不等于
BETWEEN a0 AND a1 范围匹配,[a0, a1],如果 a0 <= value <= a1,返回 TRUE(1)
IN (option, ...) 如果是 option 中的任意一个,返回 TRUE(1)
IS NULL NULL
IS NOT NULL 不是 NULL
LIKE 模糊匹配。% 表示任意多个(包括 0 个)任意字符; _ 表示任意一个字符

逻辑运算符

运算符 说明
AND 逻辑 "与":多个条件全部为 TRUE (1) 时,结果才为 TRUE (1)
OR 逻辑 "或":任意一个条件为 TRUE (1) 时,结果即为 TRUE (1)
NOT 逻辑 "非":对条件取反,若原条件为 TRUE (1),结果则为 FALSE (0)

案例

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

in语句使用

bash 复制代码
mysql> select name,math from exam_result where math =58 
    -> or math=59
    -> or math=98
    -> or math=99;
+-----------+------+
| name      | math |
+-----------+------+
| 唐三藏    |   98 |
| 猪悟能    |   98 |
+-----------+------+
2 rows in set (0.00 sec)

-- 使用 IN 条件 
mysql> SELECT name, math FROM exam_result WHERE math IN (58, 59, 98, 99); 
+-----------+------+
| name      | math |
+-----------+------+
| 唐三藏    |   98 |
| 猪悟能    |   98 |
+-----------+------+
2 rows in set (0.00 sec)

2)姓孙的同学 及 孙某同学

_ 匹配严格的一个任意字符

bash 复制代码
mysql> select name from exam_result where name like '孙%';
+-----------+
| name      |
+-----------+
| 孙悟空    |
| 孙权      |
+-----------+
2 rows in set (0.00 sec)

mysql> select name from exam_result where name like '孙_';
+--------+
| name   |
+--------+
| 孙权   |
+--------+
1 row in set (0.00 sec)

3)总分在 200 分以下的同学

bash 复制代码
select name, math+chinese+english as 总分 from exam_result 
where math+chinese+english < 200;
+-----------+--------+
| name      | 总分   |
+-----------+--------+
| 刘玄德    |    185 |
| 宋公明    |    170 |
+-----------+--------+
2 rows in set (0.00 sec)

注:WHERE 条件中使用表达式 -- 别名不能用在 WHERE 条件中

4)孙某同学,否则要求总成绩 > 200 并且 语文成绩 < 数学成绩 并且 英语成绩 > 80

bash 复制代码
 select name,math+chinese+english as 总成绩
 from exam_result
 where name like '孙_' 
 or( math+chinese+english>200 and chinese<math and english>80);
+-----------+-----------+
| name      | 总成绩    |
+-----------+-----------+
| 猪悟能    |       276 |
| 孙权      |       221 |
+-----------+-----------+
2 rows in set (0.00 sec)

5)NULL查询

bash 复制代码
-- ==和<=>区别
SELECT NULL = NULL, NULL = 1, NULL = 0; 
+-------------+----------+----------+ 
| NULL = NULL | NULL = 1 | NULL = 0 | 
+-------------+----------+----------+ 
| NULL | NULL | NULL | 
+-------------+----------+----------+ 
1 row in set (0.00 sec) 
 
SELECT NULL <=> NULL, NULL <=> 1, NULL <=> 0; 
+---------------+------------+------------+ 
| NULL <=> NULL | NULL <=> 1 | NULL <=> 0 | 
+---------------+------------+------------+ 
| 1 | 0 | 0 | 
+---------------+------------+------------+ 
1 row in set (0.00 sec) 

4. 结果排序

语法:

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

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

案例:

1)同学及 qq 号,按 qq 号排序显示

bash 复制代码
-- NULL 视为比任何值都小,升序出现在最上面 
 
SELECT name, qq FROM students ORDER BY qq; 
+-----------+-------+ 
| name | qq | 
+-----------+-------+ 
| 唐大师 | NULL | 
| 孙仲谋 | NULL | 
| 曹阿瞒 | NULL | 
| 孙悟空 | 11111 | 
+-----------+-------+ 
4 rows in set (0.00 sec)

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

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

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

bash 复制代码
SELECT name, chinese + english + math 总分 FROM exam_result 
 ORDER BY 总分 DESC; 
+-----------+--------+ 
| name | 总分 | 
+-----------+--------+ 
| 猪悟能 | 276 | 
| 孙悟空 | 242 | 
| 曹孟德 | 233 | 
| 唐三藏 | 221 | 
| 孙权 | 221 | 
| 刘玄德 | 185 | 
| 宋公明 | 170 | 
+-----------+--------+ 
7 rows in set (0.00 sec)

注:这里子句里可以使用别名,为什么?因为是先筛选出数据然后再排序

5. 筛选分页结果

语法:

bash 复制代码
-- 起始下标为 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 页

bash 复制代码
mysql> select id,name,math,english,chinese from exam_result
    -> order by id limit 3 offset 0;
+----+-----------+------+---------+---------+
| id | name      | math | english | chinese |
+----+-----------+------+---------+---------+
|  1 | 唐三藏    |   98 |      56 |      67 |
|  2 | 孙悟空    |   78 |      77 |      87 |
|  3 | 猪悟能    |   98 |      90 |      88 |
+----+-----------+------+---------+---------+
3 rows in set (0.01 sec)

mysql> select id,name,math,english,chinese from exam_result
    -> order by id limit 3,3;
+----+-----------+------+---------+---------+
| id | name      | math | english | chinese |
+----+-----------+------+---------+---------+
|  4 | 曹孟德    |   84 |      67 |      82 |
|  5 | 刘玄德    |   85 |      45 |      55 |
|  6 | 孙权      |   73 |      78 |      70 |
+----+-----------+------+---------+---------+
3 rows in set (0.01 sec)

mysql> select id,name,math,english,chinese from exam_result order by id limit 6,3;
+----+-----------+------+---------+---------+
| id | name      | math | english | chinese |
+----+-----------+------+---------+---------+
|  7 | 宋公明    |   65 |      30 |      75 |
+----+-----------+------+---------+---------+
1 row in set (0.00 sec)

6. Update

语法:

bash 复制代码
update table_name set column = expr [, column = expr ...] 
 [where ...] [order by ...] [limit ...];

案例

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

bash 复制代码
mysql> update exam_result set math =80 where name= '孙悟空';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

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

bash 复制代码
-- 数据更新,不支持 math += 30 这种语法 
mysql> update exam_result set math =math +30
    -> order by chinese+math+english limit 3;
Query OK, 3 rows affected (0.00 sec)
Rows matched: 3  Changed: 3  Warnings: 0

7. Delete

删除数据

语法:

bash 复制代码
delete from table_name [where ...] [order by ...] [limit ...]

案例

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

bash 复制代码
-- 查看原数据 
SELECT * FROM exam_result WHERE name = '孙悟空'; 
+----+-----------+-------+--------+--------+ 
| id | name | chinese | math | english | 
+----+-----------+-------+--------+--------+ 
| 2 | 孙悟空 | 174 | 80 | 77 | 
+----+-----------+-------+--------+--------+ 
1 row in set (0.00 sec) 
 
-- 删除数据 
DELETE FROM exam_result WHERE name = '孙悟空'; 
Query OK, 1 row affected (0.17 sec) 
 
-- 查看删除结果 
SELECT * FROM exam_result WHERE name = '孙悟空'; 
Empty set (0.00 sec)

删除整张表数据

bash 复制代码
-- 准备测试表 
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) 

断表截

语法:

bash 复制代码
truncate [table] table_name

注意:慎用操作

  1. 只能对整表操作,不能像 DELETE 一样针对部分数据操作
  2. 实际上 MySQL 不对数据操作,所以比 DELETE 更快,但是TRUNCATE在删除数据的时候,并不经过真正的事物,所以无法回滚
  3. 会重置 AUTO_INCREMENT 项
bash 复制代码
-- 准备测试表 
CREATE TABLE for_truncate ( 
 id INT PRIMARY KEY AUTO_INCREMENT, 
 name VARCHAR(20) 
); 
Query OK, 0 rows affected (0.16 sec) 
 
-- 插入测试数据 
INSERT INTO for_truncate (name) VALUES ('A'), ('B'), ('C'); 
Query OK, 3 rows affected (1.05 sec) 
Records: 3 Duplicates: 0 Warnings: 0 
 
-- 查看测试数据 
SELECT * FROM for_truncate; 
+----+------+ 
| id | name | 
+----+------+ 
| 1 | A | 
| 2 | B | 
| 3 | C | 
+----+------+ 
3 rows in set (0.00 sec) 
-- 截断整表数据,注意影响行数是 0,所以实际上没有对数据真正操作 
TRUNCATE for_truncate; 
Query OK, 0 rows affected (0.10 sec) 
 
-- 查看删除结果 
SELECT * FROM for_truncate; 
Empty set (0.00 sec) 
-- 再插入一条数据,自增 id 在重新增长 
INSERT INTO for_truncate (name) VALUES ('D'); 
Query OK, 1 row affected (0.00 sec)  
-- 查看数据 
SELECT * FROM for_truncate; 
+----+------+ 
| id | name | 
+----+------+ 
| 1 | D | 
+----+------+ 
1 row in set (0.00 sec) 
 
-- 查看表结构,会有 AUTO_INCREMENT=2 项 
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=utf8 
1 row in set (0.00 sec) 

8. 插入结果查询

语法:

bash 复制代码
insert into table_name [(column [, column ...])] select ...

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

bash 复制代码
-- 创建原数据表 
 
CREATE TABLE duplicate_table (id int, name varchar(20)); 
Query OK, 0 rows affected (0.01 sec) 
 
-- 插入测试数据 
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 

思路:

bash 复制代码
-- 创建一张空表 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)

9. 聚合函数

函数 说明
count([distinct] expr) 返回查询到的数据的数量
sum([distinct] expr) 返回查询到的数据的总和,不是数字没有意义
avg([distinct] expr) 返回查询到的数据的平均值,不是数字没有意义
max([distinct] expr) 返回查询到的数据的最大值,不是数字没有意义
min([distinct] expr) 返回查询到的数据的最小值,不是数字没有意义

举例:

统计班级共有多少同学

bash 复制代码
-- 使用 * 做统计,不受 NULL 影响 
 
SELECT COUNT(*) FROM students; 
+----------+ 
| COUNT(*) | 
+----------+ 
| 4 | 
+----------+ 
1 row in set (0.00 sec)

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

bash 复制代码
mysql> select count(math) from exam_result;
+-------------+
| count(math) |
+-------------+
|           7 |
+-------------+
1 row in set (0.00 sec)

-统计去重成绩
mysql> select distinct count(math) from exam_result;
+-------------+
| count(math) |
+-------------+
|           5 |
+-------------+
1 row in set (0.00 sec)

10. group by子句的使用

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

bash 复制代码
select column1, column2, .. from table group by column;

案例

  • 准备工作,创建一个雇员信息表(来自oracle 9i的经典测试表)
  1. EMP员工表
  2. DEPT部门表
  3. SALGRADE工资等级表
  • 如何显示每个部门的平均工资和最高工资

    bash 复制代码
    select deptno,avg(sal),max(sal) from EMP group by deptno; 
  • 显示每个部门的每种岗位的平均工资和最低工资

    bash 复制代码
    select avg(sal),min(sal),job, deptno from EMP group by deptno, job; 
  • 显示平均工资低于2000的部门和它的平均工资

  1. 统计各个部门的平均工资

    bash 复制代码
    select avg(sal) from EMP group by deptno 
  2. having和group by配合使用,对group by结果进行过滤

    bash 复制代码
    select avg(sal) as myavg from EMP group by deptno having myavg<2000; 
     
    --having经常和group by搭配使用,作用是对分组进行筛选,作用有些像where

注意事项

  • 分组就是把一张表按照逻辑要求拆成多个子表,然后再各自对子表进行聚合统计
  • having和where区别:
    1. 作用阶段不同
  • where :在分组(GROUP BY)之前 筛选行数据,只保留符合条件的行参与分组。

  • having :在分组(GROUP BY)之后 筛选分组结果,只保留符合条件的分组。

    1. 可操作的对象不同
  • where :只能操作原始表的列 ,不能使用聚合函数 (如COUNT()AVG())。

  • having :可以操作分组后的聚合结果(也可以用原始列,但通常配合聚合函数)。

    1. 适用场景不同
  • where:用于筛选 "行级数据"(比如:筛选工资 > 2000 的员工)。

  • having:用于筛选 "分组级数据"(比如:筛选平均工资 > 2000 的部门)。

相关推荐
Hello.Reader4 小时前
Flink SQL Window Top-N窗口榜单的正确打开方式
数据库·sql·flink
wsx_iot4 小时前
MySQL 的 MVCC(多版本并发控制)详解
数据库·mysql
敲上瘾4 小时前
MySQL主从集群解析:从原理到Docker实战部署
android·数据库·分布式·mysql·docker·数据库架构
电子_咸鱼4 小时前
【QT——信号和槽(1)】
linux·c语言·开发语言·数据库·c++·git·qt
pandarking4 小时前
[CTF]攻防世界:web-unfinish(sql二次注入)
前端·数据库·sql·web安全·ctf
程序猿20234 小时前
MySQL索引性能分析
数据库·mysql
TDengine (老段)4 小时前
TDengine 新性能基准测试工具 taosgen
大数据·数据库·物联网·测试工具·时序数据库·tdengine·涛思数据
波波仔864 小时前
行存储与列存储的区别
数据库·clickhouse·行存储·列储存
小光学长4 小时前
ssm农民养殖经验交流与分享平台bc046578(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
java·数据库·spring