欢迎来到代码驿站!

Mysql

当前位置:首页 > 数据库 > Mysql

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

时间:2022-04-21 09:45:42|栏目:Mysql|点击:

[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

上一篇:mysql之group by和having用法详解

栏    目:Mysql

下一篇:MySQL实现差集(Minus)和交集(Intersect)测试报告

本文标题:SQL实现LeetCode(196.删除重复邮箱)

本文地址:http://www.codeinn.net/misctech/199808.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有