我有两张桌子 - 学生和科目。学生表存储所有学生和科目表的列表,存储这些学生已注册的所有科目。
CREATE TABLE students
(`id` int, `name` varchar(7));
INSERT INTO students
(`id`, `name`)
VALUES
(1, 'Jason'),
(2, 'Matt'),
(3, 'Abram')
;
CREATE TABLE subjects
(`id` int,`student_id` int, `subject` varchar(15));
INSERT INTO subjects
(`id`,`student_id`, `subject`)
VALUES
(1,1, 'Math'),
(2,1, 'Physics'),
(3,2, 'Chemistry'),
(4,2, 'Math'),
(5,2, 'English'),
(6,3, 'Chemistry')
;
执行以下查询
SELECT STUD.id,STUD.name,SUB.subject
FROM students AS STUD
LEFT JOIN subjects AS SUB
ON STUD.id=SUB.student_id
;
给出这样的结果集(这不是我想要得到的)
++++++++++++++++++++++++++++++++++++
id | name | subject |
++++++++++++++++++++++++++++++++++++
| 1 | Jason | Math |
------------------------------------
| 1 | Jason | Physics |
------------------------------------
| 2 | Matt | Chemistry |
------------------------------------
| 2 | Matt | Math |
------------------------------------
| 2 | Matt | English |
------------------------------------
| 3 | Abram | Chemistry |
------------------------------------
学生在名单中重复出现。
当我尝试
时SELECT STUD.id,STUD.name,SUB.subject
FROM students AS STUD
LEFT JOIN subjects AS SUB
ON STUD.id=SUB.student_id
GROUP BY STUD.id
;
我得到了(这又错了)
++++++++++++++++++++++++++++++++++++
id | name | subject |
++++++++++++++++++++++++++++++++++++
| 1 | Jason | Math |
------------------------------------
| 2 | Matt | Chemistry |
------------------------------------
| 3 | Abram | Chemistry |
------------------------------------
我想要的结果如下:
++++++++++++++++++++++++++++++++++++++++++++++++
id | name | subject |
++++++++++++++++++++++++++++++++++++++++++++++++
| 1 | Jason | Math, Physics |
------------------------------------------------
| 2 | Matt | Chemistry,Math ,English |
------------------------------------------------
| 3 | Abram | Chemistry |
------------------------------------------------
我是关系数据库的新手。 为什么群体没有给出正确的结果? 提前谢谢。
答案 0 :(得分:1)
您可以通过
实现这一目标SELECT STUD.id,STUD.name,GROUP_CONCAT(SUB.subject) as subject
FROM students AS STUD
LEFT JOIN subjects AS SUB
ON STUD.id=SUB.student_id
GROUP BY STUD.id;
实际上,当你在sql中有一些列的组时,它会给出正确的结果,它只会返回组中的第一条记录,所以对于你想要的结果,你需要使用GROUP_CONCAT
函数返回给定列中所有逗号分隔的值。