Mysql中where與having的區(qū)別實例詳解
以一道題來做引子
牛客,SQL30 計算總和
OrderItems表代表訂單信息,包括字段:訂單號order_num和item_price商品售出價格、quantity商品數(shù)量。
order_num | item_price | quantity |
a1 | 10 | 105 |
a2 | 1 | 1100 |
a3 | 1 | 200 |
a4 | 2 | 1121 |
a5 | 5 | 10 |
a6 | 1 | 19 |
a7 | 7 | 5 |
【問題】編寫 SQL 語句,根據(jù)訂單號聚合,返回訂單總價不小于1000 的所有訂單號,最后的結(jié)果按訂單號進行升序排序。
提示:總價 = item_price 乘以 quantity
order_num | total_price |
a1 | 1050 |
a2 | 1319 |
a4 | 2242 |
先來看一看錯誤的寫法:
select order_num, sum(item_price*quantity) total_price from OrderItems group by order_num where total_price >= 1000 order by order_num
錯誤:SQL_ERROR_INFO: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'where total_price >= 1000\norder by order_num' at line 4"
上述的錯誤為:非法使用聚合函數(shù),不能在 WHERE 子句中使用聚合函數(shù)
我們的 total_price等價于sum(item_price*quantity),而在WHERE 子句中使用聚合函數(shù)
改錯
select order_num, sum(item_price*quantity) total_price from OrderItems group by order_num having total_price >= 1000 order by order_num
這樣就對了
使用having時注意:
1. 行已經(jīng)被分組。
2. 使用了聚合函數(shù)。
3. 滿足HAVING 子句中條件的分組將被顯示。
4. HAVING 不能單獨使用,必須要跟 GROUP BY 一起使用。
那么和where的區(qū)別有以下幾點:
1. WHERE 可以直接使用表中的字段作為篩選條件,但不能使用分組中的計算函數(shù)作為篩選條件; HAVING 必須要與 GROUP BY 配合使用,可以把分組計算的函數(shù)和分組字段作為篩選條件。
2. 如果需要通過連接從關(guān)聯(lián)表中獲取需要的數(shù)據(jù),WHERE 是先篩選后連接,而 HAVING 是先連接 后篩選。
3. 第二項導(dǎo)致了WHERE執(zhí)行效率高,不能使用分組中的計算函數(shù)進行篩選,而HAVING 可以使用分組中的計算函數(shù),執(zhí)行效率較低。
where、聚合函數(shù)、having在from后面的執(zhí)行順序:
where > 聚合函數(shù) > having
若需要對聚合函數(shù)對group by的結(jié)果進行過濾,只能使用having。Having語句通常與Group by語句聯(lián)合使用,用來過濾Group by語句返回的結(jié)果集,Having語句的存在彌補了Where關(guān)鍵字不能與聚合函數(shù)聯(lián)合使用的不足。
例如:查詢平均成績大于60分的同學(xué)的學(xué)號和平均成績
select s_id, AVG(s_score) s_avg from Score group by s_id Having AVG(s_score) > 60;
也可以寫成如下形式:
select s_id, AVG(s_score) s_avg from Score group by s_id Having s_avg > 60;
如果將Having改成where 就會報錯,因為where的執(zhí)行順序大于聚合函數(shù)。
總結(jié)
到此這篇關(guān)于Mysql中where與having區(qū)別的文章就介紹到這了,更多相關(guān)Mysql where與having區(qū)別內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
數(shù)據(jù)庫中GROUP?BY語句詳解、示例、注意事項
在Oracle數(shù)據(jù)庫中GROUP?BY是用于對結(jié)果集進行分組的一個關(guān)鍵字,這篇文章主要給大家介紹了關(guān)于數(shù)據(jù)庫中GROUP?BY語句詳解、示例、注意事項的相關(guān)資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2024-06-06