[https://leetcode.com/problems/delete-duplicate-emails/]
MYSQL的DETETE語(yǔ)句,包含子查詢時(shí)澳眷,如果子查詢與被刪除數(shù)據(jù)的表是一張表胡嘿,會(huì)出錯(cuò)。像下面這樣是不行的钳踊。
DELETE FROM person
WHERE id NOT IN (
SELECT MIN(Id)
FROM person
GROUP BY Email
)
解決辦法是在子查詢語(yǔ)句里再嵌套一個(gè)子查詢衷敌,像下面這樣勿侯。
DELETE FROM person
WHERE id NOT IN (
SELECT MIN(Id)
FROM (
SELECT * FROM person
) AS t
GROUP BY t.Email
);
然而,這樣就超時(shí)了缴罗,效率太低助琐,因?yàn)樽硬樵兪荢ELECT * FROM person,直接把全表拿來了面氓,沒做任何處理兵钮。較好的做法如下:
DELETE FROM Person
WHERE Id NOT IN (SELECT Id
FROM
(SELECT MIN(Id) AS Id
FROM Person
GROUP BY Email
) p
);
這么做的話最里面的子查詢查出的結(jié)果集會(huì)比較小,外面的篩選會(huì)快很多侧但。
_