0
我有一個關於course_id字段的重複記錄的SQL表。但是id字段是唯一的。我需要選擇那些對COURSE_ID重複,但我想表明,具有相同的COURSE_ID所有ID行..如何選擇只有一個字段和SQL中的所有其他字段重複的記錄?
輸出示例:
course_id|id
----- | -----
7 |2,3,6
我有一個關於course_id字段的重複記錄的SQL表。但是id字段是唯一的。我需要選擇那些對COURSE_ID重複,但我想表明,具有相同的COURSE_ID所有ID行..如何選擇只有一個字段和SQL中的所有其他字段重複的記錄?
輸出示例:
course_id|id
----- | -----
7 |2,3,6
您正在尋找group_concat()
:
select course_id, group_concat(id) as ids
from t
group by course_id
having count(*) > 1;
是這是你在找什麼?
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 |
+-----------+-------------------+
,但只顯示重複的行。如何顯示所有行 –
您需要提供更好/更多的數據和預期輸出示例。正如現在所定義的,戈登給了你正確的答案。 – ghenghy
@KuntalGupta。 。 。刪除'有'條款。這個問題表明你只想要重複的行:「我需要選擇在course_id上有重複的行。」 –