力扣數據庫題目182查找重複的電子郵箱

力扣數據庫題目182查找重複的電子郵箱mysql

題目

編寫一個 SQL 查詢,查找 Person 表中全部重複的電子郵箱。sql

示例:數據庫

+----+---------+
| Id | Email |
+----+---------+
| 1 | a@b.com |
| 2 | c@d.com |
| 3 | a@b.com |
+----+---------+code

根據以上輸入,你的查詢應返回如下結果:blog

+---------+
| Email |
+---------+
| a@b.com |
+---------+class

說明:全部電子郵箱都是小寫字母。test

來源:力扣(LeetCode)email

方案一

分組im

SELECT email
FROM test.person
GROUP BY email
HAVING count(*) > 1

方案二

where子查詢總結

SELECT DISTINCT email
FROM test.person t
WHERE (SELECT count(*) FROM test.person WHERE email = t.email) > 1

方案三

exists判斷

SELECT DISTINCT email
FROM test.person t
WHERE EXISTS(SELECT email FROM test.person WHERE email = t.email AND id <> t.id)

方案四

錶鏈接

SELECT DISTINCT a.email
FROM test.person a
INNER JOIN test.person b ON a.email = b.email AND a.id > b.id

總結

通常狀況下查詢能夠先考慮簡單查【標準單表查詢】,再考慮子查詢【SELECT或WHERE子查詢】,最後考慮錶鏈接。基本上表鏈接能夠解決幾乎全部SQL問題。

相關文章
相關標籤/搜索