【问题标题】:Mysql Select to find duplicatesMysql 选择查找重复项
【发布时间】:2011-03-30 21:34:19
【问题描述】:

谁能帮我写一个 sql select 来执行任务。 所以问题是我们有一张桌子并且有一些重复,所以我需要找到名称、街道和房屋相同的地方,并以某种方式对它们进行分组。

我几乎有this 的情况,但不同的是我想将它们分组以查找与什么重复的内容。

提前致谢。

【问题讨论】:

    标签: php sql mysql select


    【解决方案1】:

    这是假设您有一个 id 字段,该字段将与每个重复行的 GROUP_CONCAT() 函数分组:

    SELECT    t1.name, t1.street, t1.house, GROUP_CONCAT(DISTINCT t1.id) dupes
    FROM      your_table t1
    JOIN      your_table t2 ON (t2.name = t1.name AND 
                                t2.street = t1.street AND 
                                t2.house = t1.house)
    GROUP BY  t1.name, t1.street, t1.house
    HAVING    COUNT(*) > 1;
    

    测试用例:

    CREATE TABLE your_table (
       id int, 
       name varchar(10), 
       street varchar(10), 
       house varchar(10)
    );
    
    INSERT INTO your_table VALUES (1, 'a', 'b', 'c');
    INSERT INTO your_table VALUES (2, 'a', '1', 'c');
    INSERT INTO your_table VALUES (3, 'a', '2', '3');
    INSERT INTO your_table VALUES (4, 'a', 'b', 'c');
    INSERT INTO your_table VALUES (5, 'a', 'b', 'c');
    INSERT INTO your_table VALUES (6, 'c', 'd', 'e');
    INSERT INTO your_table VALUES (7, 'c', 'd', 'e');
    

    结果:

    +------+--------+-------+-------+
    | name | street | house | dupes |
    +------+--------+-------+-------+
    | a    | b      | c     | 1,5,4 |
    | c    | d      | e     | 6,7   |
    +------+--------+-------+-------+
    2 rows in set (0.03 sec)
    

    【讨论】:

    • 完美,谢谢丹尼尔。如果你不介意我会问如何在这里获得其他不重复的列,因为我需要它们显示在网格中?...我想我们必须再次更改查询..
    • @Vadim:无法以这种格式显示其他列,除非您在这些列上再次使用GROUP_CONCAT()。想象在上面的示例中,我们有另一个名为 value 的列,第 1 行的 value 为 100,第 2 行的 value 为 200,依此类推。现在,由于我们将最终结果集分组以仅显示行有重复的,value 列应该是什么? 100、400 还是 500? (因为所有这 3 条记录都分组在一行中)...但是我们可以使用 GROUP_CONCAT(value) 将此列作为逗号分隔的字段,就像 dupes 列一样。
    • @Vadim: ...另一方面,您可能想尝试下面的@wimvds 解决方案,该解决方案应该在单独的行中显示所有重复记录。
    【解决方案2】:

    要获得重复项,只需在表上使用自联接:

    select t1.id, t2.id, t1.name, t1.street, t1.house
    from table t1
    inner join table t2 on t1.name=t2.name and t1.street=t2.street and t1.house=t2.house
    where t1.id < t2.id
    

    t1.id

    【讨论】:

    • +1 for solution ,但我需要过滤它们,客户端会删除它们,所以我必须显示所有它们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-18
    • 2017-09-16
    • 1970-01-01
    • 1970-01-01
    • 2012-03-08
    • 1970-01-01
    • 2013-08-31
    相关资源
    最近更新 更多