Skip to content

Latest commit

 

History

History
41 lines (29 loc) · 1013 Bytes

196. 删除重复的电子邮箱(简单).md

File metadata and controls

41 lines (29 loc) · 1013 Bytes

[TOC]

1 原题目

编写一个 SQL 查询,来删除 Person 表中所有重复的电子邮箱,重复的邮箱里只保留 Id 最小 的那个。
+----+------------------+
| Id | Email            |
+----+------------------+
| 1  | john@example.com |
| 2  | bob@example.com  |
| 3  | john@example.com |
+----+------------------+
Id 是这个表的主键。
例如,在运行你的查询语句之后,上面的 Person 表应返回以下几行:
+----+------------------+
| Id | Email            |
+----+------------------+
| 1  | john@example.com |
| 2  | bob@example.com  |
+----+------------------+

2 解法

delete from Person where id not in (select Id from (select min(Id) as Id from Person group by Email) as p);
select * from Person;

3 知识扩展

简单的联合查询

  • SQL不允许子查询直接引用外层查询的同一张表,需要select as 生成一张临时表