#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这四个部门中工资比10000高的部门信息
SELECT department_id
FROM employees
GROUP BY id=10,20,30 40
HAVING MAX(salary) >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