《力扣》 196. 删除重复的电子邮箱,出现 You can't specify target table 'Person' for update in FROM clause 异常

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

+----+------------------+
| Id | Email            |
+----+------------------+
| 1  | [email protected] |
| 2  | [email protected]  |
| 3  | [email protected] |
+----+------------------+
Id 是这个表的主键。

例如,在运行你的查询语句之后,上面的 Person 表应返回以下几行:

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

解题思路:
错误解题:

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
)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章