Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Databases

Fredric von Stange
Fredric von Stange
3,867 Points

Advanced Solution to Multi-Subject Teachers

I've come up with a detailed solution to the Multi-Subject Teachers query.

SELECT TEACHER_ID, FIRST_NAME, LAST_NAME, SUBJECT_ID, SUBJECTS.NAME FROM CLASSES

INNER JOIN SUBJECTS ON SUBJECTS.ID = CLASSES.SUBJECT_ID

--This derived table query grabs the Teacher IDs of any teacher who teachers more than one class, that way the SELECT query above only looks at those specific teachers who teach more than one class.
INNER JOIN (
  SELECT DISTINCT TEACHERS.ID, FIRST_NAME,LAST_NAME, COUNT(DISTINCT SUBJECT_ID) AS CNT FROM TEACHERS
  INNER JOIN CLASSES ON CLASSES.TEACHER_ID = TEACHERS.ID
  INNER JOIN SUBJECTS ON SUBJECTS.ID = CLASSES.SUBJECT_ID
  GROUP BY LAST_NAME HAVING CNT > 1
  ) AS MULTSUB ON MULTSUB.ID = CLASSES.TEACHER_ID

GROUP BY SUBJECT_ID;

1 Answer

Steven Parker
Steven Parker
231,128 Points

I'm guessing the "detail" you're after is the names of the subjects taught, and that code does the job but at the cost of a separate line for each subject. There's a way to do it on one line per teacher (and without the derived table) using a function called "GROUP_CONCAT" that wasn't covered in the course:

SELECT TEACHERS.*, GROUP_CONCAT(DISTINCT SUBJECTS.NAME) AS SUBJECTS FROM TEACHERS
INNER JOIN CLASSES ON CLASSES.TEACHER_ID = TEACHERS.ID
INNER JOIN SUBJECTS ON SUBJECTS.ID = CLASSES.SUBJECT_ID
GROUP BY TEACHER_ID HAVING COUNT(DISTINCT SUBJECT_ID) > 1