问题描述:
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);