MySQL 筛选条件 & GROUP BY 分组
核心:
WHERE用来筛选行;GROUP BY用来分组统计
一、WHERE 筛选条件
1. 基本语法
select 字段名 from 表名 where 筛选条件;
执行顺序(很重要)
-
FROM:先找到操作哪张表 -
WHERE:按条件过滤数据 -
SELECT:从过滤后的结果里提取想要的字段
示例:查询年龄大于18的员工名字
select name from emp where age > 18;
逻辑:先找到emp表 → 过滤age>18的数据 → 取出name
2. 准备测试数据
-- 如果库存在就删除
drop database if exists emp_data;
-- 创建数据库
create database emp_data;
use emp_data;
-- 创建员工表
create table emp(
id int primary key auto_increment,
name varchar(20) not null,
sex enum("male","female") not null default "male",
age int(3) unsigned not null default 28,
hire_date date not null,
post varchar(50),
post_comment varchar(100),
salary double(15,2),
office int,
depart_id int
);
-- 插入测试数据
insert into emp(name, sex, age, hire_date, post, salary, office, depart_id) values
("dream", "male", 78, '20220306', "雨夜痴梦久生情", 730.33, 401, 1),
("mengmeng", "female", 25, '20220102', "teacher", 12000.50, 401, 1),
("xiaomeng", "male", 35, '20190607', "teacher", 15000.99, 401, 1),
("xiaona", "female", 29, '20180906', "teacher", 11000.80, 401, 1),
("xiaoqi", "female", 27, '20220806', "teacher", 13000.70, 401, 1),
("suimeng", "male", 33, '20230306', "teacher", 14000.62, 401, 1),
("nana", "female", 69, '20100307', "sale", 300.13, 402, 2);
3. 常用条件示例
① between ... and ... 在某个区间
闭区间,包含两边的值
-- 查询id在3~6之间员工
select * from emp where id between 3 and 6;
② like 模糊查询
-
%:匹配任意多个字符(0个或多个)
-- 查询名字包含字母o的员工姓名、薪资
select name,salary from emp where name like "%o%";
-
_:单个任意字符,一个下划线只代表1个字
-- 查询姓名刚好6个字符的员工
select name,salary from emp where name like "______";
- 函数写法
char_length(统计字符个数,更推荐)
select name,salary from emp where char_length(name) = 6;
③ or 或者
-- id>3 或者 id<6
select * from emp where id > 3 or id <6;
取反:not between,排除区间内的数据
-- 查询id不在3~6之间的数据
select * from emp where not id between 3 and 6;
④ 判断NULL 重点坑!
❌ 错误写法:post_comment = null 查不到任何数据
✅ 正确写法:is null / is not null
-- 查询岗位描述为空的员工
select name,post from emp where post_comment is null;
二、GROUP BY 分组
作用:把相同字段值的数据归为一组,搭配聚合函数做统计
聚合函数:max()最大值,min()最小值,sum()求和,count()计数,avg()平均值
语法模板
select 分组字段, 聚合函数(统计字段) from 表名 group by 分组字段;
⚠️ MySQL严格模式
only_full_group_by坑:
select后面不能直接写*,否则报错;select只能写分组字段 + 聚合函数。
1. 基础分组示例
-- 按岗位post分组,查询每个岗位最高薪资
select post, max(salary) as 最高薪资 from emp group by post;
-- 每个岗位最低薪资
select post, min(salary) as 最低薪资 from emp group by post;
-- 每个岗位薪资总和
select post, sum(salary) as 薪资总和 from emp group by post;
-- 每个岗位有多少人
select post, count(id) as 部门人数 from emp group by post;
2. group_concat() 分组拼接字符串
把同一组内的多条记录,字段内容拼成一行,非常实用
-- 按岗位分组,同一岗位的员工名字拼在一起
select post, group_concat(name) from emp group by post;
-- 同时拼接名字和薪资
select post, group_concat(name, ":", salary) from emp group by post;
3. 普通concat(不分组,单纯拼接字段)
select concat(name,"-",salary) from emp;
✅ 核心总结
-
where:过滤原始行,分组之前过滤,不能用聚合函数 -
group by:对where过滤完的数据分组,用来统计 - 判断空值:必须
is null,不能=null - 模糊查询:
%多个字符,_单个字符 - group_concat:分组后,把一组多条数据合并成字符串