LeetCode(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] |
±—±-----------------+

题解:

题目要求我们保留重复邮箱中id最小的,删除其它的,那么我们使用分组并在在输出时只显示每个分组中id最小的,这些就是我们需要保留的。因此在外层中使用not in就可以删除。
需要额外注意的,group by的值一定要在select的field中出现,因此外面加了一层select。

delete from Person where Id not in(select Id from(select min(Id) Id  from Person group by Email) t);

猜你喜欢

转载自blog.csdn.net/Fly_Fly_Zhang/article/details/95316947