【问题标题】:How to select records with duplicate just one field and all other field in SQL?如何在 SQL 中选择只有一个字段和所有其他字段重复的记录?
【发布时间】:2017-05-03 19:42:50
【问题描述】:

我有一个 SQL 表,在 course_id 字段上有重复记录。但是 id 字段是唯一的。我需要选择在 course_id 上有重复的行,但我想显示所有具有相同 course_id 的 id..

示例输出:

course_id|id
-----  | -----
7      |2,3,6

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    您正在寻找group_concat():

    select course_id, group_concat(id) as ids
    from t
    group by course_id
    having count(*) > 1;
    

    【讨论】:

    • 但它只显示重复的行。如何显示所有行
    • 您需要提供更好/更多的数据示例和预期输出。按照现在的定义,戈登已经给了你正确的答案。
    • @KuntalGupta 。 . .删除 having 子句。该问题表明您只想要具有重复项的行:“我需要选择在 course_id 上具有重复项的行。”
    【解决方案2】:

    这是你要找的吗?

    CREATE TABLE IF NOT EXISTS test (
        course_id INT UNSIGNED NOT NULL,
        id VARCHAR(500)
    );
    insert into test (course_id, id) values (7, "1,2,3");
    insert into test (course_id, id) values (7, "4,5,6");
    insert into test (course_id, id) values (7, "7,8,9");
    insert into test (course_id, id) values (8, "1,2,3");
    
    select 
      t1.course_id, 
      t1.id
    from
      test t1
      inner join 
        (select test.course_id from test group by course_id having count(*) > 1) t2
        on t1.course_id = t2.course_id;
    

    它给出了这样的结果:

    +-----------+-------+
    | course_id | id    |
    +-----------+-------+
    |         7 | 1,2,3 |
    |         7 | 4,5,6 |
    |         7 | 7,8,9 |
    +-----------+-------+
    

    或者:

    select 
      t1.course_id, 
      group_concat(t1.id) as ids
    from
      test t1
      left join 
        (select test.course_id from test group by course_id having count(*) > 1) t2
        on t1.course_id = t2.course_id
      group by t1.course_id;
    

    生产:

    +-----------+-------------------+
    | course_id | ids               |
    +-----------+-------------------+
    |         7 | 1,2,3,4,5,6,7,8,9 |
    |         8 | 1,2,3             |
    +-----------+-------------------+
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-27
      • 1970-01-01
      • 2018-12-03
      • 2012-12-24
      • 1970-01-01
      • 1970-01-01
      • 2013-08-26
      相关资源
      最近更新 更多