Wednesday, 29 June 2016

PHP / MySQL: Joining three tables and merging results











I have three tables:



Table #1: teacher



id
firstname
surname



Table #2: course



id
name


Table #3: courses_has_teachers



course_id
teacher_id



What I want to get, is the course info with the teacher(s) info. I have tried it with this query:



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



I get what I want, BUT: if a course has more than one teacher, I want to combine the results. Instead of multiple rows with same course info, I want to get one simple row with course info and a list of teachers.



NOT like this:



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



BUT this:



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


Could someone help me with this?



Answer



Use GROUP_CONCAT. try this one,



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


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...