PHP / MySQL:加入三个表并合并结果

时间:2012-09-28 07:42:15

标签: php mysql sql join

  

可能重复:
  Can I concatenate multiple MySQL rows into one field?

我有三张桌子:

表#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

有人可以帮我这个吗?

3 个答案:

答案 0 :(得分:6)

使用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

答案 1 :(得分: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格式重写了这个查询,你可能不熟悉它,但可以使用多个连接 SO 查询更容易阅读:

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

此外,您可能希望阅读我写的lengthy Q&A,您可能会发现这些内容很有用。

答案 2 :(得分:2)

尝试使用 GROUP_CONCAT GROUP BY