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

吾爱主题 阅读:170 2024-04-02 08:04:39 评论:0

[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关键字挑出较小的,然后取补集删除即可:

解法一:

?
1 2 DELETE FROM Person WHERE Id NOT IN ( SELECT Id FROM ( SELECT MIN (Id) Id FROM Person GROUP BY Email) p);

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

解法二:

?
1 2 DELETE p2 FROM Person p1 JOIN Person p2 ON p2.Email = p1.Email WHERE p2.Id > p1.Id;

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

解法三:

?
1 2 DELETE p2 FROM Person p1, Person p2 WHERE p1.Email = p2.Email AND p2.Id > p1.Id;

类似题目:

Duplicate Emails

参考资料:

https://leetcode.com/discuss/61176/simple-solution-using-a-self-join

https://leetcode.com/discuss/48403/my-answer-delete-duplicate-emails-with-double-nested-query

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

原文链接:https://www.cnblogs.com/grandyang/p/5371227.html

可以去百度分享获取分享代码输入这里。
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

【腾讯云】云服务器产品特惠热卖中
搜索
标签列表
    关注我们

    了解等多精彩内容