2

I have checked out some other questions, and I cant seem to find any that answer my specific question.

The following table is the result of this query:

SELECT teacher.teacherID, unitName FROM teacher INNER JOIN unit ON teacher.teacherID=unit.teacherID ORDER BY teacherID ASC

Table

What I actually need the result to display is this:

Table 2

Is there a way to modify my current query so that this can be achieved? I wasn't sure if this was possible in MySQL at all, but as I have learned in the past, you should never underestimate the power of a query! (this was discovered after spending time using messy nested loops trying to manipulate an array, instead i managed to do it all in a query)

EDIT: SQL Fiddle

Thanks, and I would appreciate any help!

2
  • 1
    It would be easier for us to help you if you set up a SQL Fiddle Commented Apr 19, 2013 at 19:33
  • Awesome site, I have updated question with the SQL Fiddle! Commented Apr 19, 2013 at 19:36

2 Answers 2

4

Yes, you need to use a GROUP BY and GROUP_CONCAT:

SELECT teacher.teacherID, GROUP_CONCAT(unitName)
FROM teacher
INNER JOIN unit ON teacher.teacherID=unit.teacherID
GROUP BY teacher.teacherID
ORDER BY teacherID ASC

This query works directly in your SQL Fiddle.

Sign up to request clarification or add additional context in comments.

1 Comment

Excellent, thankyou this answer worked perfectly! I will accept this as soon as stackoverflow lets me!
2

A slight tweak to alexn's answer to match your formatting with spaces after the comma:

SELECT teacher.teacherID, GROUP_CONCAT(unitName SEPARATOR ', ')
FROM teacher
INNER JOIN unit ON teacher.teacherID=unit.teacherID
GROUP BY teacher.teacherID
ORDER BY teacherID ASC

1 Comment

how would you do this but getting rid of duplicate unitNames ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.