编写一个 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 |
+----+------------------+
解题思路:
错误解题:
delete from Person
where
id not in (select min(id) as id from Person group by Email
)
抛出异常:
You can't specify target table 'Person' for update in FROM clause
这是因为MySQL不允许同时查询和删除一张表,我们可以通过子查询的方式包装一下即可避免这个报错
正确解题:
delete from Person
where
id not in (select temp.id from --加上这个外层筛选可以避免You can't specify target table for update in FROM clause错误(select min(id) as id from Person group by Email) as temp
)