首页 > 数据库 > MySQL

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

[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

参考资料:

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实现删除重复邮箱内容请搜索潘少俊衡以前的文章或继续浏览下面的相关文章希望大家以后多多支持潘少俊衡!

版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。
本文地址:/shujuku/MySQL/100242.html

留言与评论(共有 0 条评论)
   
验证码:

潘少俊衡

| 桂ICP备2023010378号-4

Powered By EmpireCMS

爱享小站

中德益农

谷姐神农

环亚肥料

使用手机软件扫描微信二维码

关注我们可获取更多热点资讯

感谢潘少俊衡友情技术支持