2017-05-03 77 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    | 
+-----------+-------------------+ 
相關問題