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上有重复的行。” –