sql中having的使用


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 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM