Delete Duplicate Emails --leetcode

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

+----+------------------+
| 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:

+----+------------------+
| Id | Email            |
+----+------------------+
| 1  | john@example.com |
| 2  | bob@example.com  |
+----+------------------+
https://leetcode.com/problems/delete-duplicate-emails/description/

solution:

我想了半天  而後不是有group 可是我發現須要我保留小的那個
delete from Person  where  Id not in (select iid from 
(select Min(Id) as iid from Person p1  group by Email  ) as temp )

原來還能夠這麼關聯  學習了
DELETE p1 FROM Person p1 INNER JOIN Person p2
WHERE p1.Email = p2.Email AND p1.Id > p2.Id;

DELETE FROM p1 USING Person p1 INNER JOIN Person p2
WHERE p1.Email = p2.Email AND p1.Id > p2.Id;

git地址:https://github.com/woshiyexinjie/leetcode-xingit

相關文章
相關標籤/搜索