LeetCode(196):删除重复的电子邮箱 Delete Duplicate Emails(SQL)

2019.12.11 LeetCode 从零单刷个人笔记整理(持续更新)

github:https://github.com/ChopinXBP/LeetCode-Babel

传送门:删除重复的电子邮箱

编写一个 SQL 查询,来删除 Person 表中所有重复的电子邮箱,重复的邮箱里只保留 Id 最小 的那个。

+----+------------------+
| Id | Email            |
+----+------------------+
| 1  | [email protected] |
| 2  | [email protected]  |
| 3  | [email protected] |
+----+------------------+
Id 是这个表的主键。

例如,在运行你的查询语句之后,上面的 Person 表应返回以下几行:

+----+------------------+
| Id | Email            |
+----+------------------+
| 1  | [email protected] |
| 2  | [email protected]  |
+----+------------------+


DELETE p1
FROM Person p1, Person p2
WHERE p1.email = p2.email AND p1.Id > p2.Id;

#MySQL不允许select和delete操作同一个表,会出现以下错误
#错误:You can't specify target table 'person' for update in FROM clause
#解决办法:添加一个临时表
DELETE FROM Person
WHERE Id NOT IN(
    SELECT Id
    FROM(
        SELECT MIN(Id) AS id
        FROM Person
        GROUP BY Email
    ) temp
);




#Coding一小时,Copying一秒钟。留个言点个赞呗,谢谢你#

发布了246 篇原创文章 · 获赞 316 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_20304723/article/details/103491178