WHERE和HAVING的區別?
where子句和having子句一樣,都是用於條件判斷的.這也是很多人區分不開的主要原因.不知道什麼時候用什麼的子句判斷.既然定義了這兩個判斷子句,就肯定是有區別的,下面從四方面解釋一下
1. where子句和having子句都可以使用的場景.
2. 只可以用where,不可以用having的情況.
3. 只可以用having,不可以用where情況.
4. 總結
1.where子句和having子句都可以使用的場景.
SELECT id,price from goodshaving id>1 LIMIT 0,5;
SELECTid,price from goods where id>1 LIMIT 0,5;
解釋:在這種情況下和where的效果是等效的,但是如果沒有篩選having所需欄位(having id>1)就會報錯! 因為having是從前篩選的欄位再篩選,而where是從資料表中的欄位直接進行的篩選的。
2. 只可以用where,不可以用having的場景
SELECT price from goods having id>1 LIMIT 0,5; (報錯:1054 - Unknown column'id' in 'having clause')
由於having 是篩選組的.而查詢語句沒有將id這個欄位篩選,所以這種場景下只能用where.如下:
SELECT price from goods where id>1 LIMIT 0,5;
3.只可以用having,不可以用where的場景
· GROUP BY 後只能 用having
SELECT id, AVG(price) avgprice,goodsName FROMgoods GROUP BY id having avgprice > 6000;
SELECT id, AVG(price)avgprice,goodsName FROM goods GROUP BY id where avgprice > 6000;
(錯:1064 - You have an error in your SQL syntax; check the manual thatcorresponds to your MySQL server version for the right syntax to use near'where avgprice > 6000' at line 1)
但是WHERE可以這麼使用 :SELECT id, AVG(price)avgprice,goodsName FROM goods WHERE id>100 GROUP BY id
· having能夠使用統計函式,但是where不能使用
SELECT sum(price) fromgoods group by goodsName having sum(price)>210;
SELECT sum(price) from goods groupby goodsName where sum(price)>210;
(1064 - You have an error in your SQL syntax; check the manualthat corresponds to your MySQL server version for the right syntax to use near'where sum(price)>210' at line 1)
· having子句中可以使用欄位別名,而where不能使用
SELECT id as asd, goodsName FROM goodshaving asd>5;
SELECTid as asd, goodsName FROM goods where asd>5; (1054 - Unknown column 'asd' in'where clause')