聚合函數
where 后面不能直接使用聚合函數
處理函數
題目
編寫一個 SQL 查詢,查找 Person 表中所有重復的電子郵箱。
示例:
+----+---------+
| Id | Email |
+----+---------+
| 1 | a@b.com |
| 2 | c@d.com |
| 3 | a@b.com |
+----+---------+
根據以上輸入,你的查詢應返回以下結果:
+---------+
| Email |
+---------+
| a@b.com |
+---------+
說明:所有電子郵箱都是小寫字母。
1、使用having過濾分組select email from person group by email having count(email) > 1
2、使用臨時表方法select email from (select email,count(email) as num from person group by eamil) as new where new.num >1
說明
1、having通常用在聚合函數前面,對聚合函數進行過濾,(MAX、MIN、COUNT、SUM)
2、having通常和group by 一起連用,因為where不能加在group by的后面
3. where 和 having 的區別?
1. where 在分組之前進行限定,如果不滿足條件,則不參與分組。having在分組之后進行限定,如果不滿足結果,則不會被查詢出來
2. where 后不可以跟聚合函數,having可以進行聚合函數的判斷。
mysql執行語句順序,嚴格遵循次順序,不能改變
select
from
where
group by
having
order by