2017-05-03 41 views

回答

0

您正在寻找group_concat()

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

,但只显示重复的行。如何显示所有行 –

+0

您需要提供更好/更多的数据和预期输出示例。正如现在所定义的,戈登给了你正确的答案。 – ghenghy

+0

@KuntalGupta。 。 。删除'有'条款。这个问题表明你只想要重复的行:“我需要选择在course_id上​​有重复的行。” –

0

是这是你在找什么?

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    | 
+-----------+-------------------+ 
相关问题