为什么使用子查询来获取原始表?

时间:2019-01-29 21:37:44

标签: mysql sql subquery

我遇到了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)的子查询

1 个答案:

答案 0 :(得分:4)

这是MySQL中的黑客。 MySQL不允许DELETEUPDATE直接引用被修改的表。额外的子查询可具体化该表并允许代码工作。

许多人会改用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;