# HAVING的使用(作用:用来过滤数据)
# 咱们之前过滤数据用的是WHERE,杀出个程咬金
# GROUP BY分组之后,提到的HAVING
# 从需求出发
# 练习:查询各个部门中最高工资比10000高的部门信息
# 用WHERE (错误的写法)
SELECT department_id,MAX(salary)
FROM employees
where MAX(salary)>10000
GROUP BY department_id;
# 正确的写法
# 要求1:如果过滤条件中使用了聚合函数,则必须使用HAVING来替换WHERE
SELECT department_id,MAX(salary)
FROM employees
HAVING MAX(salary)>10000
GROUP BY department_id;
# 要求2:HAVING必须声明在GROUP BY的后面
SELECT department_id,MAX(salary)
FROM employees
GROUP BY department_id
HAVING MAX(salary)>10000;
# 规范 比如:叫爸爸
# 思考:如果没有GROUP BY,还能不能用HAVING?
SELECT department_id,MAX(salary)
FROM employees
HAVING MAX(salary)>10000;
# 要求3:虽然没有GROUP BY,用HAVING没有报错,但是在实际开发当中,我们使用HAVING的前提是SQL中使用了GROUP BY
# 练习:查询部门id为10,20,30,40这4个部门中最高工资比10000高的部门信息
# 方式1 推荐,执行效率高于方式2
SELECT department_id,MAX(salary)
FROM employees
WHERE department_id IN(10,20,30,40)
GROUP BY department_id
HAVING MAX(salary)>10000;
# 方式2
SELECT department_id,MAX(salary)
FROM employees
GROUP BY department_id
HAVING MAX(salary)>10000 AND department_id IN(10,20,30,40);
# 结论1:当过滤条件中有聚合函数时,则此过滤条件必须声明在HAVING中
# 结论2:当过滤条件中没有聚合函数时,则此过滤条件声明在WHERE中或HAVING中都可以,但是建议大家声明在WHERE中
/* WHERE与HAVING的对比
1 从适用范围上来讲,HAVING的适用范围更广
2 如果过滤条件中没有聚合函数,这种情况下,WHERE的执行效率高于HAVING