Silentdoer

导航

having在SQL里的作用以及和where的区别

1.where和having都是过滤数据的作用,且都是根据某个“字段”来过滤数据,区别在于:

where是根据from的表里的行数据来过滤,比如where aa > 1表示查出from的表里aa字段>1的所有行;

where可以不和group by一起用;

 

而having是对已经分组(聚合)的组进行过滤,所以它肯定是要和group by是一起用的,

而且由于having是对聚合后的组进行过滤,所以它要求先分组得到了组后,再根据这些组来匹配条件过滤,具体一点是:

select aaa, count(*) as count from table_a group by aaa having count > 10,注意这里having的字段只能是aaa或count,而不能是table_a里的其他字段

,因为having是对分组后得到的临时表的数据的过滤,临时表里只有aaa和count两个字段了;

 

所以having其实可以用内嵌sql替换,如上面的可以改成(但是having可能内部会做优化):

select* from (select aaa, count(*) as count from table_a group by aaa) as tmp where count > 10

即从分组数据暂存的临时表tmp里select*,然后再where count > 10,这个外层的where就是上面的having的功能;

 

between and是用于限定某个字段在某个区间里,比如select * from table_a where aaa between 30 and 60,即过滤出aaa >= 30并且 aaa <= 60的所有数据。

posted on 2023-12-20 14:42  Silentdoer  阅读(12)  评论(0编辑  收藏  举报