MySQL自娱—6.分组函数
分组函数
- 功能 用作统计使用 又称为聚合函数或统计函数或分组函数
- 分类
- sum 求和
select sum(salary) from employees;
- avg 平均值
- max 最大值
- min 最小值
- count 统计非null个数
- 参数支持哪些类型?
- sum avg一般用于处理数值型 max min count可以处理任何类型
- 以上分组函数都忽略Null值
- 和distinct搭配实现去重运算
- count函数的详细介绍
- select count(*) from employees; 用来统计总行数
- select count(1) from employees; 用来统计总行数
- 效率问题
MYISAM存储引擎下, count(*)的效率高
INNODB存储引擎下, count(*)和count(1)效率差不多, 比count(字段)要高一些
- 和分组函数一同查询的字段有限制 要求是group by后的字段
- 补充 datediff函数第一个参数减第二个参数
分组查询
select column, group_function(column)
from table
where condition
group by group_by_expression
order by column;
明确 where 一定放在from后面
select 分组函数,列 (要去出现在group by的后面)
from 表
where 筛选条件
group by 分组的列表
order by 子句
- 注意 查询列表必须特殊,要求是分组函数和group by后出现的字段
select max(salary), job_id
from employees
group by job_id;
select count(*),location_id
from departments
group by location_id;
select avg(salary), department_id
from employees
where email like "%a%"
group by department_id;
select max(salary), manager_id
from employees
where commission_pct is not null
group by manager_id;
- 分组后的筛选
select count(*), department_id
from employees
group by department_id
having count(*)>2;
select max(salary), job_id
from employees
where commission_pct is not null
group by job_id
having max(salary) > 12000;
select min(salary), manager_id
from employees
where manager_id>102
group by manager_id
having min(salary)>5000;
- 特点
- 分组查询中的筛选条件分为两类
数据源 位置 关键字
- 分组前筛选 原始表 group by子句的前面 where
- 分组后筛选 分组后的结果集 group by自居的后边 having
- 注意
- 分组函数做条件肯定是放在having字句中
- 能用分组前筛选的就有限考虑使用分组前
- group by后边还支持哪些东西
- 按表达式或函数分组
select count(*) c, length(last_name) len_name
from employees
group by len_name
having c>5;
扩展 where后边不支持别名
- 按多个字段分组
select avg(salary), department_id,job_id
from employees
where department_id is not null
group by job_id,department_id
order by avg(salary) desc;
- group by子句支持单个字段分组,多个字段分组(多个字段之间用逗号隔开.没有顺序要求),表达式或函数(用的较少)
- 也可以添加排序(排序放在整个分组查询的最后)