在集合中查找以获取带逗号的单独值

Find in set to get the separate values with comma

之前我问过同样的问题(Join table with comma issue (MySQL))关于在列中用逗号加入table。

我有两个 table,table 结构如下:

第一个Table姓名:学生

id   | name   | course_id
——————————————————————————
1      David     1,3 
2      Peter     2,4
3      Shawn     2,6

第二个 Table 姓名:主题

id    |    subject
———————————————————
1          English
2          Maths
3          Science
4          Geographic
5          Accounting
6          Art & Design

我试过这个find_in_set方法(Search with comma-separated value mysql),但是无法得到实际结果。我希望实际结果如下所示:

id   | name | subject_name
——————————————————————————
1      David   English,Science
2      Peter   Maths,Geographic
3      Shawn   Maths,Art & Design

我正在使用以下代码:

SELECT student.id as id,student.name as name,student.subject as subject_name
FROM student
INNER JOIN subject
ON FIND_IN_SET(subject.id, student.course_id) > 0

但是结果如下所示:

id   | name | subject_name
——————————————————————————
1      David   English
2      David   Science
3      Peter   Maths
4      Peter   Geographic
5      Shawn   Maths
6      Shawn   Art & Design

希望有人指导我如何解决这个问题。谢谢。

像这样

SELECT student.id as id, student.name as name, GROUP_CONCAT(subject.subject) as subject_name
FROM student
INNER JOIN subject
ON FIND_IN_SET(subject.id, student.course_id) > 0
GROUP BY student.id, student.name

通常我们不会在 SQL 查询中连接所有内容,但您可以这样做

SELECT CONCAT_WS(' ', student.id, student.name, GROUP_CONCAT(subject.subject)) as concated_value
FROM student
INNER JOIN subject
ON FIND_IN_SET(subject.id, student.course_id) > 0
GROUP BY student.id, student.name