🧩 一、什么是聚合查询
聚合查询:
👉 是指对多行数据进行统计计算,返回单个结果值(比如总数、平均数等)。
常与 GROUP BY 一起使用,也可以单独使用。
🧮 二、MySQL 常见聚合函数(完整列表)
| 函数名 | 含义 | 示例 | 说明 |
|---|---|---|---|
COUNT() | 统计数量 | COUNT(*) | 统计行数 |
SUM() | 求和 | SUM(salary) | 计算总工资 |
AVG() | 求平均 | AVG(age) | 计算平均年龄 |
MAX() | 最大值 | MAX(score) | 最高分 |
MIN() | 最小值 | MIN(price) | 最低价格 |
GROUP_CONCAT() | 组内拼接 | GROUP_CONCAT(name) | 拼接成字符串 |
VAR_SAMP() | 样本方差 | VAR_SAMP(num) | 统计分析用 |
STDDEV_SAMP() | 样本标准差 | STDDEV_SAMP(num) | 统计分析用 |
CREATE TABLE employee ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50), department VARCHAR(50), salary DECIMAL(10,2), age INT );
INSERT INTO employee (name, department, salary, age) VALUES ('张三', '技术部', 8000, 25), ('李四', '技术部', 9500, 28), ('王五', '销售部', 7000, 24), ('赵六', '销售部', 7200, 27), ('孙七', '人事部', 6500, 26);
🧠 四、聚合函数示例(单表)
1️⃣ 统计总人数
SELECT COUNT(*) AS total_employees FROM employee;
结果:
total_employees
---------------
5
2️⃣ 求平均工资
SELECT AVG(salary) AS avg_salary FROM employee;
3️⃣ 求最高工资、最低工资
SELECT MAX(salary) AS max_salary, MIN(salary) AS min_salary FROM employee;
4️⃣ 求工资总额
SELECT SUM(salary) AS total_salary FROM employee;
5️⃣ 拼接所有员工姓名(用逗号分隔)
SELECT GROUP_CONCAT(name) AS names FROM employee;
MySQL 查询语句的执行顺序核心知识
🧩 一、完整 sql 语句结构
select column_list
from table_name
where condition
group by group_columns
having condition_after_group
order by column_list
limit offset, count;
🧠 二、mysql 实际执行顺序
💡 写的顺序 ≠ 执行的顺序
| 实际执行顺序 | 关键字 | 作用 |
|---|---|---|
| 1️⃣ | from | 指定数据来源的表 |
| 2️⃣ | where | 过滤行(行级筛选) |
| 3️⃣ | group by | 分组(把多行变为一组) |
| 4️⃣ | having | 过滤组(组级筛选) |
| 5️⃣ | select | 选择要返回的列 |
| 6️⃣ | order by | 排序 |
| 7️⃣ | limit | 限制输出数量 |
📘 三、逐个讲解(小写版)
1️⃣ from —— 从哪张表取数据
select * from employee;
👉 从 employee 表取全部数据。
2️⃣ where —— 行级筛选
select * from employee
where department = '技术部';
👉 只保留部门是“技术部”的记录。
⚠️ where 不能使用聚合函数(比如 count、avg)。
3️⃣ group by —— 分组聚合
select department, avg(salary) as avg_salary
from employee
group by department;
👉 按部门分组,统计每个部门的平均工资。
4️⃣ having —— 组级筛选
select department, avg(salary) as avg_salary
from employee
group by department
having avg_salary > 8000;
👉 筛选平均工资大于 8000 的部门。
| 区别 | where | having |
|---|---|---|
| 作用阶段 | 分组前 | 分组后 |
| 能否用聚合函数 | ❌ 不行 | ✅ 可以 |
5️⃣ select —— 选择列
select name, salary from employee;
👉 只返回 name 和 salary 两列。
6️⃣ order by —— 排序
select name, salary
from employee
order by salary desc;
👉 按工资从高到低排列。
也可多列排序:
order by department asc, salary desc;
7️⃣ limit —— 限制返回数量
select * from employee
limit 5;
👉 返回前 5 条记录。
分页:
limit 10, 5; -- 从第 11 条开始,取 5 条
🧱 四、执行顺序对比
| 写的顺序 | 实际执行顺序 |
|---|---|
| select | 5 |
| from | 1 |
| where | 2 |
| group by | 3 |
| having | 4 |
| order by | 6 |
| limit | 7 |
🧮 五、综合例子
select department, avg(salary) as avg_salary
from employee
where age > 24
group by department
having avg_salary > 8000
order by avg_salary desc
limit 2;