我遇到了Leetcode的一个问题。
https://leetcode.com/problems/delete-duplicate-emails/
下面是一种方法:
DELETE FROM Person WHERE
Id NOT IN (SELECT MIN(p.Id) FROM (SELECT * FROM Person) p
Group by p.Email);
我想知道为什么它需要一个用于表本身(SELECT MIN(p.Id) FROM (SELECT * FROM Person)
而不是(SELECT MIN(p.Id) FROM Person p)
的子查询
答案 0 :(得分:4)
这是MySQL中的黑客。 MySQL不允许DELETE
或UPDATE
直接引用被修改的表。额外的子查询可具体化该表并允许代码工作。
许多人会改用JOIN
来写:
DELETE p
FROM Person p JOIN
(SELECT p2.email, MIN(p2.ID) as min_id
FROM person p2
GROUP BY p2.email
) pp
ON pp.email = p.email
WHERE p.id > pp.id;