我在course_id字段上有一个带有重复记录的SQL表。但是id字段是唯一的。我需要选择在course_id上有重复的行但我想要显示所有具有相同course_id的id ..
示例输出:
course_id|id
----- | -----
7 |2,3,6
答案 0 :(得分:0)
您正在寻找["1396", "12", "22", "12", "33", "42"]
:
group_concat()
答案 1 :(得分: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 |
+-----------+-------------------+