• *Delete Duplicate Emails


    题目

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


    思路:

    编写SQL删除Person表中所有的重复email条目,只保留Id最小的唯一email记录。

    其中,Id是表的主键。

    解法一:

    # Write your MySQL query statement below
    DELETE p1 FROM Person p1 INNER JOIN Person p2
    WHERE p1.Email = p2.Email AND p1.Id > p2.Id;

    上述SQL使用了MySQL DELETE语法的多表语法I,参阅:https://dev.mysql.com/doc/refman/5.0/en/delete.html

    DELETE [LOW_PRIORITY] [QUICK] [IGNORE]
        tbl_name[.*] [, tbl_name[.*]] ...
        FROM table_references
        [WHERE where_condition]

    解法二:

    # Write your MySQL query statement below
    DELETE FROM p1 USING Person p1 INNER JOIN Person p2
    WHERE p1.Email = p2.Email AND p1.Id > p2.Id;

    上述SQL使用了MySQL DELETE语法的多表语法II

    DELETE [LOW_PRIORITY] [QUICK] [IGNORE]
        FROM tbl_name[.*] [, tbl_name[.*]] ...
        USING table_references
        [WHERE where_condition]

    解法三:???

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

    注意,使用下面的SQL会抛出运行时错误:

    # Write your MySQL query statement below
    DELETE FROM Person WHERE ID NOT IN (SELECT MIN(Id) FROM Person GROUP BY Email);
    Runtime Error Message:    You can't specify target table 'Person' for update in FROM clause
    Last executed input:    {"headers": {"Person": ["Id", "Email"]}, "rows": {"Person": []}}

    上述SQL的错误原因为:

    在MySQL中,禁止在FROM子句中指定被更新的目标表。

    
    
  • 相关阅读:
    jmeter如何监控服务器CPU、内存、i/o等资源
    Red hat下搭建简易实用的SVN服务器
    ICPC2021(济南)打星队线上打铁游记
    「笔记」如何优雅的造数据
    软件开发中,不要把重点放在“雕琢”上
    对公司数据库管理的看法
    工作两年来 对VB开发的感想
    对数学的一点认识
    学习面向对象语言的感受
    中国 奥运 加油!
  • 原文地址:https://www.cnblogs.com/hygeia/p/4710106.html
Copyright © 2020-2023  润新知