[SQL]LeetCode196. 刪除重複的電子郵箱 | Delete Duplicate Emails

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-tbbhioqp-md.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

Write a SQL query to delete all duplicate email entries in a table named Person, keeping only unique emails based on its smallest Id.git

+----+------------------+
| Id | Email            |
+----+------------------+
| 1  | john@example.com |
| 2  | bob@example.com  |
| 3  | john@example.com |
+----+------------------+
Id is the primary key column for this table.

For example, after running your query, the above Person table should have the following rows:github

+----+------------------+
| Id | Email            |
+----+------------------+
| 1  | john@example.com |
| 2  | bob@example.com  |
+----+------------------+

編寫一個 SQL 查詢,來刪除 Person 表中全部重複的電子郵箱,重複的郵箱裏只保留 Id 最小 的那個。微信

+----+------------------+
| Id | Email            |
+----+------------------+
| 1  | john@example.com |
| 2  | bob@example.com  |
| 3  | john@example.com |
+----+------------------+
Id 是這個表的主鍵。

例如,在運行你的查詢語句以後,上面的 Person 表應返回如下幾行:this

+----+------------------+
| Id | Email            |
+----+------------------+
| 1  | john@example.com |
| 2  | bob@example.com  |
+----+------------------+

517ms
1 DELETE
2 FROM person
3 WHERE id NOT IN (SELECT t.id
4                  FROM (
5                         SELECT min(id) AS id
6                         FROM Person
7                         GROUP BY email
8                       ) t);

500msspa

 1 # Write your MySQL query statement below
 2 DELETE
 3 FROM Person
 4 WHERE Id IN (
 5     SELECT Id
 6     FROM (
 7         SELECT
 8         Id, Email, (Email = @prev) AS dup, @prev := Email
 9         FROM (
10             SELECT Email, Id
11             FROM Person
12             ORDER BY 1, 2
13         ) AS sorted,
14         (SELECT @prev := NULL) AS init
15     ) AS t
16     WHERE dup IS TRUE
17 )

505mscode

1 # Write your MySQL query statement below
2 delete from Person where Id not in(select t.Id from (select min(Id) id from Person b group by Email) t)
相關文章
相關標籤/搜索