編寫一個 SQL 查詢,來刪除 Person 表中所有重複的電子郵箱,重複的郵箱裏只保留 Id 最小 的那個。
+----+------------------+
| Id | Email |
+----+------------------+
| 1 | [email protected] |
| 2 | [email protected] |
| 3 | [email protected] |
+----+------------------+
Id 是這個表的主鍵。
例如,在運行你的查詢語句之後,上面的 Person 表應返回以下幾行:
+----+------------------+
| Id | Email |
+----+------------------+
| 1 | [email protected] |
| 2 | [email protected] |
+----+------------------+
MySQL 不能對同一張表,一邊進行查詢一邊進行刪除操作,報錯:You can't specify target table 'Person' for update in FROM clause
替換的操作是: 查詢先生成一張臨時表,然後對臨時表查詢對原表進行刪除,這樣就解決了不能一邊查詢一遍刪除的問題
Delete
from Person
where Id not in(
select need.id
from(
select min(Id) as id
from Person
group by Email
) as need
)