1. 程式人生 > >196. 刪除重複的電子郵箱

196. 刪除重複的電子郵箱

編寫一個 SQL 查詢,來刪除 Person 表中所有重複的電子郵箱,重複的郵箱裡只保留 Id 最小 的那個。

+----+------------------+
| Id | Email            |
+----+------------------+
| 1  | [email protected] |
| 2  | [email protected]  |
| 3  | [email protected] |
+----+------------------+
Id 是這個表的主鍵。

例如,在執行你的查詢語句之後,上面的 Person 表應返回以下幾行:

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

思路:SELF JOIN 表,然後設定條件DELETE

DELETE p1
FROM Person AS p1, Person AS p2
WHERE (p1.Email=p2.Email) AND (p1.ID > p2.ID)