★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-nncugalv-md.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Write a SQL query to find all duplicate emails in a table named Person
.git
+----+---------+ | Id | Email | +----+---------+ | 1 | a@b.com | | 2 | c@d.com | | 3 | a@b.com | +----+---------+
For example, your query should return the following for the above table:github
+---------+ | Email | +---------+ | a@b.com | +---------+
Note: All emails are in lowercase.算法
編寫一個 SQL 查詢,查找 Person
表中全部重複的電子郵箱。微信
示例:app
+----+---------+ | Id | Email | +----+---------+ | 1 | a@b.com | | 2 | c@d.com | | 3 | a@b.com | +----+---------+
根據以上輸入,你的查詢應返回如下結果:spa
+---------+ | Email | +---------+ | a@b.com | +---------+
說明:全部電子郵箱都是小寫字母。code
GROUP BY
和臨時表算法:重複的電子郵件存在屢次。要計算每封電子郵件的存在時間,咱們能夠使用如下代碼。htm
1 select Email, count(Email) as num 2 from Person 3 group by Email;
| Email | num | |---------|-----| | a@b.com | 2 | | c@d.com | 1 |
以此做爲臨時表,咱們能夠獲得以下解決方案。blog
1 select Email from 2 ( 3 select Email, count(Email) as num 4 from Person 5 group by Email 6 ) as statistic 7 where num > 1 8 ;
GROUP BY
和HAVING
條件向a添加條件的一種更經常使用的方法GROUP BY
是使用該HAVING
子句,這更簡單,更有效。
因此咱們能夠重寫上面的解決方案。
1 select Email 2 from Person 3 group by Email 4 having count(Email) > 1;