如何将多个值连接到一列结果中

时间:2019-04-12 04:26:54

标签: mysql join

我有下表:

老师

+------------+-------------+
|ID          |Name         |
+------------+-------------+
|1           |teacher1     |
|2           |teacher2     |
|3           |teacher3     |
+------------+-------------+

教学

+------------+-------------+
|teacher_ID  |specialty    |
+------------+-------------+
|1           |specialty1   |
|1           |specialty2   |
|2           |specialty1   |
|3           |specialty5   |
|3           |specialty8   |
|3           |specialty2   |
+------------+-------------+

我想做的是:我想要一个查询,它可以为我提供以下内容:

+--------------+------------------------------------------+
|teacher_name  |specialties                               |
+--------------+------------------------------------------+
|teacher1      |specialty1, specialty2                    |
|teacher2      |specialty1                                |
|teacher3      |specialty5, specialty8, specialty2        |
+--------------+------------------------------------------+

因此,我希望每个老师的专长都按列值连接到上面。使用MySQL甚至可以做到吗?如果是这样,请让我知道。

2 个答案:

答案 0 :(得分:1)

我们可以在此处尝试使用GROUP_CONCAT

SELECT
    t1.ID,
    t1.Name,
    GROUP_CONCAT(t2.specialty) AS specialties
FROM teacher t1
LEFT JOIN teaches t2
    ON t1.ID = t2.teacher_ID
GROUP BY
    t1.ID,
    t1.Name;

答案 1 :(得分:0)

使用group_concat()

select Name as teacher_name,group_concat(specialty) as specialties
from teacher a inner join teaches b
on a.id=b.teacher_id
group by b.teacher_id,name