zoukankan      html  css  js  c++  java
  • *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子句中指定被更新的目标表。

    
    
  • 相关阅读:
    模板jinja2常用方法
    简单实用的日志类CLog (Python版)
    Databus架构分析与初步实践
    AWS API 2.0签名规范
    django学习——通过get_FOO_display 查找模型中的choice值
    Twitter如何在数千台服务器上快速部署代码?
    mysql 添加索引 mysql 如何创建索引
    sql中的like和正则的区别
    python2.7运行出现的Warning: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode
    Python命令模块argparse学习笔记(四)
  • 原文地址:https://www.cnblogs.com/hygeia/p/4710106.html
Copyright © 2011-2022 走看看