where和having的区别

来源:互联网 发布:硕鼠软件 编辑:程序博客网 时间:2024/04/27 13:26
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)
    fromstudentScore
    groupby studentid
    havingleft(studentid, 1)='0'
  select studentid, avg(score)
    fromstudentScore
    whereleft(studentid, 1)='0'
    groupby studentid
这种情况下哪个会快一点

解析:
select studentid, avg(score) from studentScore group by studentidhaving left(studentid, 1)='0'

1、分组汇总
2、过滤非法项
left(studentid,1)='0'是个效率不很高的过滤条件,如果分组会使数据量极大减少(比如每个人有几十门课),而且要过滤掉的只是很小一部分学生,这种写法会有比较高的效率

select studentid, avg(score) from studentScore whereleft(studentid, 1)='0' group by studentid

1、过滤非法项
2、分组汇总
虽然left(studentid,1)='0'是个效率不很高的过滤条件,但是如果你要从几百万学生中找到几十个学生3-5门功课的平均分,还是应该很明智的选择它
 
 
ps:having和where并没有谁好谁不好的区别,我觉得最重要的是看需要,适合用哪个就用哪个
0 0
原创粉丝点击