Leetcode SQL[196] Delete-duplicate-emails
Leetcode SQL[196] Delete-duplicate-emails
编写一个 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 |
±—±-----------------+
思路
MySQL数据的一个特点,就是在update,insert ,和delete这些更新数据库的操作时在语句中不能引用该表
法一:多表删除,from的时候将person 指定别名为 p1 和 p2 然后删除p1即可。
新知识点:同张表指定多个别名
法二:用到了两个子查询 只用一个会报错因为直接引用了?
代码
Method 1
delete p1 from person as p1, person as p2
where p1.email = p2.email
and p1.id > p2.id
Method 2
delete from person
where id not in (select p.id
from(select min(id) as id from person
group by email)as p);
收获
加强练习。