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.
+----+------------------+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|
| 3| john@example.com |
+----+------------------+
Id is the primary key column for this table.
+----+------------------+这道题让我们删除重复邮箱,那我们可以首先找出所有不重复的邮箱,然后取个反就是重复的邮箱,都删掉即可,那么我们如何找出所有不重复的邮箱呢,我们可以按照邮箱群组起来,然后用Min关键字挑出较小的,然后取补集删除即可:
| Id | Email|
+----+------------------+
| 1| john@example.com |
| 2| bob@example.com|
+----+------------------+
解法一:
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 p2WHERE 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实现LeetCode(196.删除重复邮箱)的文章就介绍到这了,更多相关SQL实现删除重复邮箱内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
推荐阅读
- 关于QueryWrapper|关于QueryWrapper,实现MybatisPlus多表关联查询方式
- MybatisPlus使用queryWrapper如何实现复杂查询
- python学习之|python学习之 实现QQ自动发送消息
- 孩子不是实现父母欲望的工具——林哈夫
- opencv|opencv C++模板匹配的简单实现
- Node.js中readline模块实现终端输入
- 【Leetcode/Python】001-Two|【Leetcode/Python】001-Two Sum
- java中如何实现重建二叉树
- leetcode|leetcode 92. 反转链表 II
- 人脸识别|【人脸识别系列】| 实现自动化妆