7

可能重复:
我可以将多个 MySQL 行连接到一个字段中吗?

我有三张桌子:

表格1:teacher

id
firstname
surname

表#2:course

id
name

表3:courses_has_teachers

course_id
teacher_id

我想要得到的是带有老师信息的课程信息。我已经用这个查询试过了:

SELECT * FROM 
teacher, course, courses_has_teachers
WHERE
courses_has_teachers.teacher_id = teacher.id
AND
course.id = courses_has_teachers.course.id

我得到了我想要的,但是:如果一门课程有不止一位老师,我想结合结果。而不是具有相同课程信息的多行,我想获得一个包含课程信息和教师列表的简单行。

不像这样:

Name      | Teacher
--------------------
Course 1  | Person 1
Course 1  | Person 2

但是这个:

Name      | Teacher
------------------------------
Course 1  | Person 1, Person 2

有人可以帮我解决这个问题吗?

4

3 回答 3

7

使用GROUP_CONCAT. 试试这个,

SELECT  a.name, GROUP_CONCAT(CONCAT(firstname, ' ', surname))
FROM    course a
        INNER JOIN courses_has_teachers b
            ON a.id = b.course_id
        INNER JOIN teacher c
            ON b.teacher_id = c.iD
GROUP BY a.name
于 2012-09-28T07:45:56.317 回答
3

您想使用名为 group_concat 的 mysql 函数来实现此目的。您的查询将类似于以下内容:

SELECT courseName, group_concat(teacherName) FROM 
teacher, course, courses_has_teachers
WHERE
courses_has_teachers.teacher_id = teacher.id
AND
course.id = courses_has_teachers.course.id
GROUP BY courseName

我以 ANSI-92 格式重新编写了这个查询,您可能不熟悉,但它可以使具有多个连接的查询易于阅读:

SELECT 
    courseName, 
    group_concat(teacherName) 
FROM 
    teacher
        join course
            on courses_has_teachers.teacher_id = teacher.id
        join courses_has_teachers
            on course.id = courses_has_teachers.course.id
WHERE
    // Any conditions you want on the query
GROUP BY
    courseName

此外,您可能想阅读我写的冗长的问答,您可能会觉得这很有用。

于 2012-09-28T07:44:02.977 回答
2

尝试使用GROUP_CONCATGROUP BY

于 2012-09-28T07:43:43.730 回答