-- HAVING (用来过滤数据的)
#在之前 过滤数据用WHERE
#在GROUP BY分组后,有 HAVING
#使用 WHERE (错误,无法运行)
SELECT department_id,MAX(salary)
FROM employees
WHERE MAX(salary) > 10000
GROUP BY department_id;
#使用 HAVING (正确)
#要求1:若过滤条件中使用了聚合函数,则必须使用HAVING
#要求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
#查询指定部门的工资
#1. (执行效率高,推荐)
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 中
-- 1.从适用范围上说, HAVING 的适用范围更加广泛
-- 2.如果过滤条件中没有聚合函数,WHERE 的执行效率要高于 HAVING