[leetcode数据库05] 196. 删除重复的电子邮箱
作者:互联网
leetcode数据库题目,简单题,面试中出现频率为45%
题目描述:
编写一个 SQL 查询,来删除 Person 表中所有重复的电子邮箱,
重复的邮箱里只保留 Id 最小 的那个。
+----+------------------+
| Id | Email |
+----+------------------+
| 1 | john@example.com |
| 2 | bob@example.com |
| 3 | john@example.com |
+----+------------------+
Id 是这个表的主键。
例如,在运行你的查询语句之后,上面的 Person 表应返回以下几行:
+----+------------------+
| Id | Email |
+----+------------------+
| 1 | john@example.com |
| 2 | bob@example.com |
+----+------------------+
提示:
执行 SQL 之后,输出是整个 Person 表。
使用 delete 语句。
题目答案:
-- 官方题解
delete p1 from Person p1,
Person p2
where
p1.Email = p2.Email and p1.Id > p2.Id
-- 大佬题解(比官方题解效率高)
delete from Person as a
where not exists
(select need.id
from
(select min(Id) as id from Person group by Email) as need
where need.id = a.id
)
delete from Person
where id not in
(select need.id
from
(select min(Id) as id from Person group by Email) as need
)
既然是删除重复的邮箱,又是保留重复邮箱里的id最小的那个,那么可以先查出来重复邮箱中id最小的那一批集合,然后对比原表中id,删除不在集合中的id即可
知识点:delete,内连接,group by,not in,not exists
标签:Email,05,196,leetcode,Person,+----+------------------+,need,Id,id 来源: https://blog.csdn.net/qq_35354855/article/details/117948755