如何将具有许多这种关系的列分组?

时间:2018-11-29 18:23:23

标签: mysql join

距离我上次发布已经有很长时间了(今天我头疼得要命),所以如果这个问题被解决,我会明白的。

我要联接多个表以获取如下所示的数据(https://meta.stackexchange.com/questions/73566/is-there-markdown-to-create-tables在StackOverflow上确实没有表视图吗?)

| course_name    | student_name  |  credit_type  | 
| course_1       | student_1     |  credit_2     |
| course_1       | student_1     |  credit_3     |
| course_1       | student_1     |  credit_4     |
| course_1       | student_2     |  credit_1     |
| course_1       | student_2     |  credit_2     |
| course_1       | student_2     |  credit_3     |
| course_1       | student_2     |  credit_4     |
| course_1       | student_3     |  credit_1     |
| course_1       | student_3     |  credit_2     |
| course_1       | student_3     |  credit_3     |
| course_1       | student_3     |  credit_4     |
| course_2       | student_1     |  credit_1     |
| course_2       | student_1     |  credit_2     |
| course_2       | student_1     |  credit_3     |
| course_2       | student_1     |  credit_4     |
| course_2       | student_2     |  credit_1     |
| course_2       | student_2     |  credit_2     |
| course_2       | student_2     |  credit_3     |
| course_2       | student_2     |  credit_4     |
| course_2       | student_3     |  credit_1     |
| course_2       | student_3     |  credit_2     |
| course_2       | student_3     |  credit_3     |
...........

我想要将每个学生的所有学分归为一组的数据,所以看起来像这样

| course_name  |    student_name  | credit_type                              |
| course_1     |    student_1     | credit_2, credit_3, credit_4             |
| course_1     |    student_2     | credit_1, credit_2, credit_3, credit_4   |
| course_1     |    student_3     | credit_1, credit_3, credit_4             |
| course_2     |    student_1     | credit_1, credit_2, credit_4             |
| course_2     |    student_2     | credit_1, credit_2, credit_4             |
| course_2     |    student_3     | credit_1, credit_2, credit_4             |
| ............ |    ..............| ..., ..., ..., ..., ..., ..., ..., ..., .|

我知道GROUP_CONCAT,只是不确定在这种情况下如何实现它。 请记住,这是一个遗留系统,很快就会被淘汰。

最简单的方法是什么?

如果您能帮助我,我将非常感谢。

1 个答案:

答案 0 :(得分:1)

您只需在此处的两列(GROUP BY)上course_name, student_name

SELECT
  course_name, 
  student_name, 
  GROUP_CONCAT(credit_type)
FROM your_table
GROUP BY course_name, student_name