Reputation: 47
Can someone help me trouble shoot my syntax i spent 1 hour on it yet i cant figure it out.
I have 3 tables:
**Student**
-ID (UUID)
email (String)
**Teacher**
-ID (UUID)
email (String)
**StudentTeacher**
-ID (UUID)
studentId (UUID)
teacherId (UUID)
I have an initiate query which returns some studentId
SELECT studentId FROM TeacherStudents WHERE teacherId IN ('123', '456') GROUP BY studentId HAVING COUNT(DISTINCT teacherId) = 2
I would like to join the results with Students table so i can return the email address
However, this is not working
SELECT email FROM TeacherStudents WHERE teacherId IN ('123', '456') GROUP BY studentId HAVING COUNT(DISTINCT teacherId) = 2 INNER JOIN Students on TeacherStudents.studentId = Students.id
It returns an error.
Upvotes: 0
Views: 34
Reputation: 86716
The generalised case, to get all columns from the Student table...
SELECT
Students.*
FROM
(
SELECT studentId
FROM TeacherStudents
WHERE teacherId IN ('123', '456')
GROUP BY studentId
HAVING COUNT(DISTINCT teacherId) = 2
)
StudentsOfInterest
INNER JOIN
Students
ON StudentsOfInterest.studentId = Students.id
Upvotes: 1
Reputation: 1269763
The correct syntax is:
SELECT s.studentId, s.email
FROM TeacherStudents ts JOIN
Students s
ON ts.studentId = s.id
WHERE ts.teacherId IN (123, 456)
GROUP BY s.studentId, s.email
HAVING COUNT(DISTINCT ts.teacherId) = 2 ;
Notes:
WHERE
is a SQL clause that follows the FROM
clause.JOIN
s are an operator in the FROM
clause.TeacherId
is probably a number, so do not use single quotes.SELECT
match the GROUP BY
. You can drop s.studentId
from the SELECT
if you really want to.Upvotes: 1