`

where与having的区别

 
阅读更多
注意:查询中的执行步骤:先分组,在聚合,最后筛选。。。(where ,分组,集合函数,筛选)

1.用的地方不一样

   where可以用于select、update、delete和insert...into语句中。
   having只能用于select语句中
 2.执行的顺序不一样
   where的搜索条件是在执行语句进行分组之前应用
   having的搜索条件是在分组条件后执行的
   即如果where和having一起用时,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门功课的平均分,还是应该很明智的选择它
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics