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 trialGreg Kaleka
39,021 PointsEven More Subqueries!
You can get a slightly cleaner table by wrapping the full query as a subquery of another simpler query:
SELECT FIRST_NAME, LAST_NAME FROM TEACHERS WHERE ID IN (
SELECT DISTINCT TEACHERS.ID FROM SUBJECTS
JOIN CLASSES ON SUBJECTS.ID = CLASSES.SUBJECT_ID
JOIN TEACHERS ON CLASSES.TEACHER_ID = TEACHERS.ID
WHERE GRADE IS NULL
);
The advantage of this is you get a table that doesn't include the ID field from the TEACHERS table.
Ryan Dainton
17,164 PointsSELECT FIRST_NAME, LAST_NAME
FROM TEACHERS
WHERE ID IN
(SELECT TEACHER_ID FROM CLASSES WHERE SUBJECT_ID IN
(SELECT ID FROM SUBJECTS WHERE GRADE IS NULL));
This also works for maximum subqueries!!
2 Answers
Paul Brubaker
14,290 PointsIf having the ID column is not desired, why not use GROUP BY instead of a sub-query, like this:
SELECT FIRST_NAME, LAST_NAME FROM TEACHERS
JOIN CLASSES ON CLASSES.TEACHER_ID = TEACHERS.ID
JOIN SUBJECTS ON SUBJECTS.ID = CLASSES.SUBJECT_ID
WHERE SUBJECTS.GRADE IS NULL
GROUP BY TEACHERS.ID;
Mark Chesney
11,747 PointsThat's excellent, Greg!
I came up with this query, which was definitely inspired by your previous subquery posts:
SELECT * FROM TEACHERS WHERE ID IN (
SELECT TEACHER_ID FROM CLASSES WHERE SUBJECT_ID IN (
SELECT ID FROM SUBJECTS WHERE GRADE IS NULL
)
)
Mohammed Ismail
7,190 PointsMohammed Ismail
7,190 PointsYes, thats much cleaner! Thanks Greg!!!