Mysql中having與where的區(qū)別小結
一. 簡介
where
對查詢數據進行過濾
having
用于對已分組的數據進行過濾【having和group by 必須配合使用(有having必須出現group by)】
二. 用法
where
select * from table where sum(字段)>100
having
select * from table group by 字段 having 字段>10
三.區(qū)別
1. 被執(zhí)行的數據來源不同
where是數據從磁盤讀入內存的時候進行判斷,【數據分組前進行過濾】
而having是磁盤讀入內存后再判斷?!緦Ψ纸M之后的數據再進行過濾】
所以:使用where比用having效率要高很多。
2. 執(zhí)行順序不一樣
Where>Group By>Having
MySQL解釋sql語言時的執(zhí)行順序:
SELECT DISTINCT <select_list> FROM <left_table> <join_type> JOIN <right_table> ON <join_condition><strong> WHERE</strong> <where_condition> GROUP BY <group_by_list><strong> HAVING</strong> <having_condition> ORDER BY <order_by_condition> LIMIT <limit_number>
3. where不可以使用字段的別名,但是having可以
select name as aa from student where aa > 100 (錯誤) select name as aa from student group name having aa > 100 (正確)
4. having能夠使用聚合函數當做條件,但是where不能使用,where只能使用存在的列當做條件
select * as aa from student where count(*) > 1 (錯誤) select * from student group name having count(name) > 1 (正確)
注意:能用where就用where
5. 多表關聯查詢時,where先篩選再聯接,having先聯接再篩選
找出所有在'IT'部門且薪水高于10000的員工:(在聯接之前先進行了篩選)
SELECT e.employee_name, d.department_name FROM employees e JOIN departments d ON e.department_id = d.department_id WHERE e.salary > 10000 AND d.department_name = 'IT';
找出每個客戶下訂單的總金額超過1000的客戶及其訂單總金額:(先聯表,基于分組后的聚合結果來過濾)
SELECT c.customer_name, SUM(o.order_amount) AS total_amount FROM customers c JOIN orders o ON c.customer_id = o.customer_id GROUP BY c.customer_name HAVING SUM(o.order_amount) > 1000;
總結
- where子句在數據被聯接和分組之前應用,用于過濾行
- having子句在數據被聯接、分組和聚合之后應用,用于過濾分組
到此這篇關于Mysql中having與where的區(qū)別小結的文章就介紹到這了,更多相關Mysql having與where區(qū)別內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Linux環(huán)境下設置MySQL表名忽略大小寫的方法小結
在MySQL中,表名的大小寫敏感性取決于操作系統(tǒng)和MySQL的配置,在Unix/Linux系統(tǒng)上,表名通常是區(qū)分大小寫的,由于之前MySQL未設置忽略表名大小寫導致數據查詢失敗等問題,所以本文給大家介紹了Linux環(huán)境下設置MySQL表名忽略大小寫的方法,需要的朋友可以參考下2024-06-06

