美文网首页
[LeetCode] Delete Duplicate Emai

[LeetCode] Delete Duplicate Emai

作者: 空城为谁留 | 来源:发表于2018-03-16 16:22 被阅读0次

    中文题目

    编写一个SQL查询来删除Person表中所有重复的电子邮件,在重复的邮件中只保留Id最小的邮件。

    +----+------------------+
    | Id | Email |
    +----+------------------+
    | 1 | john@example.com |
    | 2 | bob@example.com |
    | 3 | john@example.com |
    +----+------------------+
    Id是这个表的主键.
    例如,在运行查询之后,上面的 Person 表应显示以下几行:

    +----+------------------+
    | Id | Email |
    +----+------------------+
    | 1 | john@example.com |
    | 2 | bob@example.com |
    +----+------------------+


    英文题目

    Write a SQL query to delete all duplicate email entries in a table named Person, keeping only unique emails based on its smallest Id.

    +----+------------------+
    | 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:

    +----+------------------+
    | Id | Email |
    +----+------------------+
    | 1 | john@example.com |
    | 2 | bob@example.com |
    +----+------------------+


    参考答案

    方法一:

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

    方法二:

    DELETE p2 FROM Person p1 JOIN Person p2 
    ON p2.Email = p1.Email WHERE p2.Id > p1.Id;
    

    方法三:

    DELETE p2 FROM Person p1, Person p2
    WHERE p1.Email = p2.Email AND p2.Id > p1.Id;
    

    相关文章

      网友评论

          本文标题:[LeetCode] Delete Duplicate Emai

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