打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
LeetCode——Delete Duplicate Emails(巧用mysql临时表)
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  |+----+------------------+Note:Your output is the whole Person table after executing your sql. Use delete statement.

此题有两个解法:

我初步尝试用以下sql解决问题(要删除的记录Id肯定大于相同内容的Id):

delete p1 from Person p1, Person p2 where p2.id > p1.id and p2.Email = p1.Email;

但是无法通过,究其原因是在sql语句中,SELECTDELETE操作不能同时存在.

答案一

因此尝试新的解法,直接使用删除语句,结果如下所示:

delete p1 from Person p1, Person p2 where p1.id > p2.id and p1.Email = p2.Email;

此答案通过测试,但是效率较低.

答案二

后续思考中发现,可以使用临时表解决SELECTDELETE同时存在的问题,答案如下所示:

DELETE FROM PersonWHERE Id IN(    SELECT Id FROM        (SELECT p1.Id as Id FROM Person p1, Person p2 WHERE p1.Email = p2.Email AND p1.Id > p2.Id) AS TEMP)

此解决方案完美解决问题,且sql语句比较清晰明了.

PS:
如果您觉得我的文章对您有帮助,请关注我的微信公众号,谢谢!

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
MySql中4种批量更新的方法
用SQL语句去掉重复的记录(转)
mysql的auto
Mybatis增删改查mapper文件写法详解
数据分析人必掌握的数据库语言——SQL指南第七期
MySql快速插入以及批量更新
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服