SQL中Having與Where的區別

Cesar發表於2016-01-24

含義

  • where
    在分組之前就進行選擇操作

  • having
    having在分組操作之後才進行選擇操作,所以having可以選擇聚合函式

eg:

// 下面這句是可以的
SELECT COUNT(*) FROM A
WHERE A.a1>0
GROUP BY a2;
//但是下面就不行
SELECT COUNT(*) FROM A
WHERE A.a1>0 and count(*)>1
GROUP BY a2;
//必須要改為having
SELECT COUNT(*) FROM A
WHERE A.a1>0
GROUP BY a2
HAVING COUNT(*)>1

相關文章