leetcode196-Delete Duplicate Emails(删除重复并且id较大的数据)
问题描述:
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 |
+----+------------------+
问题求解:
1、MySQL DELETE语法的多表语法:创造临时表,找到删除条件,进行删除更新。
delete p1 from Person p1 inner join Person p2
where p1.email=p2.email and p1.id>p2.id;
或者:
delete from p1 using Person p1 inner join Person p2
where p1.email=p2.email and p1.id>p2.id;
2、
delete from Person where Id
not in (select * from (select min(Id) from Person p group by email) mindata);
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
