sql語句中where和having的區別

最近在項目中用到數據庫的讀取發現where和having的區別

where:在group by 之前過濾數據

having:在group by 之前過濾數據

舉個栗子

id target_id time type  
1 2 500 2  
2 2 400 0  
3 3 450 0  
4 3 350 0  
5 4 600 0  
6 4 550 0  
7 5 400 0  
8 5 300 0  
9 6 700 0  

select * from table where type is not 2 group by target_id order by max(time) desc;

結果如下,因爲先要把type是2的行(第一行)刪除再分組所以第二行出現在結果中

id target_id time type
1 2 400 0
3 3 450 0
5 4 600

0

7 5 400 0
9 6 700 0

select * from table group by target_id having type is not 2 order by max(time) desc;

結果如下,因爲要先根據target_id分組但是因爲第一行的type是2所以在最後的結果中被過濾掉

id target_id time type
3 3 450 0
5 4 600 0
7 5 400 0
9 6 700 0

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章