标签:
where 和having有什么区别?
where 是group by之前进行筛选,having是group by 之后进行统计的筛选,一般having会和group by一起使用,结合聚合函数,统计之后进行筛选。
例子:
表Student(id,name)
要求:编写Sql从student表中查出Name字段重复3条以上的记录,并编写sql删除这些重复记录
首先查出重复三条以上的记录:
select name from student group by name having count(name)>3
然后删除这些重复记录,只保留一条
select * from student where name in ( select name from student group by name having count(*)>3)
and id not in(select min(id) from student group by name having count(*)>3 )
分析:name在重复记录之中,但是id不是这些重复记录的最小id
数据完全重复比较容易解决,使用distinct 关键字,就可以得到无重复记录的结果集:
select distinct * from tableName
使用顺序: where.....group by....having.....order by
标签:
原文地址:http://www.cnblogs.com/janneystory/p/5619100.html