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