本节涉及的sql语句:
-- HAVING -- 错误示例 SELECT deptno FROM t_emp WHERE AVG(sal)>=2000 GROUP BY deptno; 因为where的执行优先于group by,所以在为分组之前,AVG函数不知道对那些结果进行求平均值,也就是说函数执行的优先级要在group by 之后,函数经常出现在select中,也就是说select优先级要在group by 之后,等select 结果出炉后,在进行排序,最后进行limit分页,所以各子句的优先顺序如下: FROM > WHERE > GROUP BY > SELECT > ORDER BY > LIMIT -- HAVING SELECT deptno,AVG(sal) FROM t_emp GROUP BY deptno HAVING AVG(sal)>=2000; -- 查询每个部门中,1982年以后入职的员工超过2个人的部门编号 SELECT deptno FROM t_emp WHERE hiredate>"1982-01-01" GROUP BY deptno HAVING count(*)>=2; -- HAVING中不能拿一个聚合函数和一个具体的字段比较,可以和数字比较 SELECT deptno FROM t_emp WHERE hiredate>"1982-01-01" GROUP BY deptno HAVING count(*)>=2 AND sal>=AVG(sal);
引入HAVING字句原因:
以上语句执行报错
采用HAVING
练习