欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SQL实现LeetCode(196.删除重复邮箱)

程序员文章站 2024-01-01 11:04:04
[leetcode] 196.delete duplicate emails 删除重复邮箱write a sql query to delete all duplicate email entries...

[leetcode] 196.delete duplicate emails 删除重复邮箱

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

这道题让我们删除重复邮箱,那我们可以首先找出所有不重复的邮箱,然后取个反就是重复的邮箱,都删掉即可,那么我们如何找出所有不重复的邮箱呢,我们可以按照邮箱群组起来,然后用min关键字挑出较小的,然后取补集删除即可:

解法一:

delete from person where id not in
(select id from (select min(id) id from person group by email) p);

我们也可以使用内交让两个表以邮箱关联起来,然后把相同邮箱且id大的删除掉,参见代码如下:

解法二:

delete p2 from person p1 join person p2 
on p2.email = p1.email where p2.id > p1.id;

我们也可以不用join,而直接用where将两表关联起来也行:

解法三:

delete p2 from person p1, person p2
where p1.email = p2.email and p2.id > p1.id;

类似题目:

duplicate emails

参考资料:

到此这篇关于sql实现leetcode(196.删除重复邮箱)的文章就介绍到这了,更多相关sql实现删除重复邮箱内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

上一篇:

下一篇: