Delete Duplicate Emails

/ mysql / 没有评论 / 370浏览

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

这是LeetCode一道简单的mysql题目。虽然简单,却包含了mysql的一些坑。

题目简单翻译下:写一个sql语句,删除重复Email字段的数据,保留ID最小的数据。

这里面包含两个坑:

1、使用delete删除数据时,如果使用别名,delete的格式为delete a from tableName a

2、使用delete删除数据时,如果涉及的子查询和目标删除表是同个表时,要用多一个查询把子查询select出来,用别名。

我的sql语句:

 delete e from Person  e
where e.Id in (select f.Id from (SELECT c.Id FROM Person c WHERE c.Email IN(SELECT a.Email FROM Person a GROUP BY a.Email HAVING COUNT(a.Email)>=2))f)  
and e.Id not in (select g.Id from (SELECT min(b.Id) as Id FROM Person b GROUP BY b.Email) g)
点击这里给我发消息
嘿!有什么能帮到您的吗?