源自刘嘉老师的课程《数据库开发》,课堂笔记
Group By 分组
Group By 是什么?
- 结果集,每一行都是一组;而且表示一行(或多行)中某一列(或者多列)具有相同的值
ANSI标准
-
Select后面接的结果集字端只有两种
-
要么是group by出现的字段
selete deptno,count(*) as cnt from emp group by deptno
-
要么是group by后出现的字段+聚合函数的组合
-
-
错误案例:
selete deptno, count(*) as cnt from emp # 这里的count(*)count的是啥?没有意义。一定要有group by这样一个聚合函数,才能有这样的一个逻辑 select deptno, name, count(*) as cnt from emp group by deptno # 这里的name的意义不明确,不知道指向的是结果集中的哪一个name(有可能结果集之中有多个name)
select和group by
-
规则之外可以放入select子句中的内容
- 用户定义的函数、窗口函数、非关联的标量自查询返回的常量、标量值。
-
例子:
select deptno, count(*) as cnt from emp group by deptno select 'hello' as msg, 1 as num, deptno, (select count(*) from emp) as total count(*) as cnt from emp group by deptno
group by 必须要保证后面接的每一个组,他们组合起来的内容必须是有唯一的行,只有这样才能进行聚合。
Group by 中 count(*)问题
- count(*)需要返回一个>0的值。
- 对于NULL值,他也会对NULL值进行一个单独的分组。
SQL的执行顺序
Select xx, max(a)
From T
Where b > 3
Group bu xx
Having max(a) > ??
Order by xx
- 上述sql语句的执行顺序为:
- From …生成一个很大的中间结果集
- where … 对From操作选出来的每一条结果集进行比对,把不符合条件的结果进行剔除
- Group by … 本质上是进行排序。把相似的特征放到一起然后进行Group by。是对where操作的结果集的一个压缩
- having … 对group by的结果进行一个聚合。
- select … having昨晚之后,通过select进行读取
- order by …对最终的结果进行排序
- 查询优化器能够管道的就是select和where;group by是没法管的。