SQL DML 你可能不知道的?

为什么表的别名可以出现在select 查询列表中
为什么列的别名可以出现在order by 字句中
为什么列的别名不能出现在group by 字句中
为什么from 字句中设置了表的别名之后在select 查询列表中就不能使用原表名
……
 
理解了select 语句的执行顺序, 这些问题就变得有趣而不是烦恼
完整的select查询语句结构:
select  colun,group_function   -- 5   
from table         --1 
[where condition ]       ---2
[group by group_by_expression ]    --3
[having group_condition ]      --4
[order by column]     -- 6

执行顺序:
1 拿到表
2 对表数据进行过滤
3 符合条件的通过group by 进行分组
4 分组数据通过having 字句进行组函数过滤
5 从得到的结果集中选取需要显示的字段
6 按照指定的字段进行排序,作为最终结果呈现给用户

明白了select  语句的执行顺序,下面的规律也变得有趣……
1 select 字句:
  可以使用子查询
 
2 where 子句:
 不允许对select 中的字段使用分组函数
 可以使用子查询
 
 
3 group by 子句:
  紧接在where 字句的后边
  如果添加group by 字句,必须保证出现在select 字句中字段,如果出现的位置不在组函数中,必须出现在group by 字句中
  出现在group by 字句中出现的字段,可以不出现在select 字句中
 
 
4 having 字句:
  可以使用组函数
  可以使用子查询
 
 
5 order by 字句:
  可以使用表的列别名
  可以使用组函数
  可以含有算术表达式的
 
 
一个示例:
拿到每个部门的员工的个数
select d.deptno x ,count(e.empno) num  --5   -- 拿到部门号和员工数
from emp e  full join dept2 d  --1
on e.deptno=d.deptno  
where e.empno<>7499 --2
group by d.deptno  --3
having d.deptno in (10,20,30,40)  --4
order by  x  --6
原文地址:https://www.cnblogs.com/czjone/p/1829525.html