問題:this
Write a SQL query to delete all duplicate email entries in a table named Person
, keeping only unique emails based on its smallest Id.spa
+----+------------------+ | Id | Email | +----+------------------+ | 1 | john@example.com | | 2 | bob@example.com | | 3 | john@example.com | +----+------------------+ Id is the primary key column for this table.
For example, after running your query, the above Person
table should have the following rows:code
+----+------------------+ | Id | Email | +----+------------------+ | 1 | john@example.com | | 2 | bob@example.com | +----+------------------+
解決:it
① 能夠首先找出全部不重複的郵箱,而後取個反就是重複的郵箱,都刪掉便可,那麼咱們如何找出全部不重複的郵箱呢,咱們能夠按照郵箱羣組起來,而後用Min關鍵字挑出較小的,而後取補集刪除便可。962mstable
DELETE FROM Person
WHERE Id NOT IN
(SELECT Id FROM
(SELECT MIN(Id) Id FROM Person GROUP BY Email) p
);email
② 使用內交讓兩個表以郵箱關聯起來,而後把相同郵箱且Id大的刪除掉;954mssed
DELETE p2 FROM Person p1 JOIN Person p2
ON p2.Email = p1.Email WHERE p2.Id > p1.Id;im
③ 直接用where將兩表關聯起來;1444ms。tab
DELETE p2 FROM Person p1,Person p2
WHERE p1.Email = p2.Email AND p2.Id > p1.Id;ping