(SQL)196. 删除重复的电子邮箱

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

+----+------------------+
| Id | Email            |
+----+------------------+
| 1  | [email protected] |
| 2  | [email protected]  |
| 3  | [email protected] |
+----+------------------+
Id 是这个表的主键。
例如,在运行你的查询语句之后,上面的 Person 表应返回以下几行:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/delete-duplicate-emails
 

题解一:1、通过子查询找出所有重复的行; 

select b.Id from Person a,Person b where b.Id>a.Id and b.Email=a.Email

                2、由于MySQL不能 select 和 delete 操作同一张表,因此创建临时表tem;

(select Id from (select b.Id from Person a,Person b where b.Id>a.Id and b.Email=a.Email) as tem)

                3、 在此表中的数据应该全部删除;

delete 
      from Person 
where 
      Id 
in
      (select Id from (select b.Id from Person a,Person b where b.Id>a.Id and b.Email=a.Email) as tem);

题解二:利用两表联立的笛卡尔积,直接delete

delete 
      b
from 
      Person a,Person b   
where 
      b.id>a.id and b.Email=a.Email;

 

你可能感兴趣的:(SQL,leetcode)