美文网首页
MYSQL-DELETE

MYSQL-DELETE

作者: lunabird | 来源:发表于2016-11-18 16:49 被阅读37次

    [https://leetcode.com/problems/delete-duplicate-emails/]
    MYSQL的DETETE语句,包含子查询时,如果子查询与被删除数据的表是一张表,会出错。像下面这样是不行的。

    DELETE FROM person 
    WHERE id NOT IN (
    SELECT MIN(Id) 
    FROM person
    GROUP BY Email
    )
    

    解决办法是在子查询语句里再嵌套一个子查询,像下面这样。

    DELETE FROM person 
    WHERE id NOT IN ( 
    SELECT MIN(Id) 
    FROM ( 
    SELECT * FROM person 
    ) AS t 
    GROUP BY t.Email
    );
    

    然而,这样就超时了,效率太低,因为子查询是SELECT * FROM person,直接把全表拿来了,没做任何处理。较好的做法如下:

    DELETE FROM Person
    WHERE Id NOT IN (SELECT Id 
               FROM 
                (SELECT MIN(Id) AS Id 
                 FROM Person 
                 GROUP BY Email
                ) p
              );
    

    这么做的话最里面的子查询查出的结果集会比较小,外面的筛选会快很多。
    _

    相关文章

      网友评论

          本文标题:MYSQL-DELETE

          本文链接:https://www.haomeiwen.com/subject/hycspttx.html