1.用的地方不一样
where可以用于select、update、delete和insert...into语句中。
having只能用于select语句中
2.执行的顺序不一样
WHERE 子句在聚合之前起作用,不能放在 GROUP BY 子句之后;WHERE 子句指定的检索条件中,不能引用包含在聚合函数中的输入源中的列或者表达式
HAVING 子句在聚合之后起作用,不能放在 GROUP BY 子句之前;HAVING 子句的检索条件中,如果引用了输入源的列或表达式,要求要么出现在聚合函数中,要么出现在 GROUP BY 子句中
即如果where和hav【】‘’-;=ing一起用时,where会先执行,having后执行
3.子句有区别
where子句中的条件表达式having都可以跟,而having子句中的有些表达式where不可以跟;
having子句可以用集(/聚)合函数(sum、count、avg、max和min),而where子句不可以。
有些地方两者都可以用,比如:
select studentid, avg(score)
from studentScore
group by studentid
having left(studentid, 1)=’0’
select studentid, avg(score)
from studentScore
where left(studentid, 1)=’0’
group by studentid
这种情况下哪个会快一点
解析:
select studentid, avg(score) from studentScore group by studentid having left(studentid, 1)=’0’
1、分组汇总
2、过滤非法项
left(studentid, 1)=’0’是个效率不很高的过滤条件,如果分组会使数据量极大减少(比如每个人有几十门课),而且要过滤掉的只是很小一部分学生,这种写法会有比较高的效率
select studentid, avg(score) from studentScore where left(studentid, 1)=’0’ group by studentid
1、过滤非法项
2、分组汇总
虽然left(studentid, 1)=’0’是个效率不很高的过滤条件,但是如果你要从几百万学生中找到几十个学生3-5门功课的平均分,还是应该很明智的选择它
ps:having和where并没有谁好谁不好的区别,我觉得最重要的是看需要,适合用哪个就用哪个