天天看點

where和having的差別

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并沒有誰好誰不好的差別,我覺得最重要的是看需要,适合用哪個就用哪個