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  | [email protected] |
| 2  | [email protected]  |
| 3  | [email protected] |
+----+------------------+

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  | [email protected] |
| 2  | [email protected]  |
+----+------------------+

问题求解:

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);

你可能感兴趣的:(数据库)