mercredi 22 juillet 2015

Select ID which has relationship to list of IDs from another table

  • I am using an SQLite 3 database.
  • I have 2 tables with a many-to-many relationship. As a result, I also have a junction table to persist this relationship. Below is a representation of something similar to what I have, with made up data etc.

Teacher Table: +----+------------+ | ID | Name | +----+------------+ | 1 | TeacherOne | | 2 | TeacherTwo | +----+------------+

StudentTable: +----+------------+ | ID | Name | +----+------------+ | 1 | StudentOne | | 2 | StudentTwo | +----+------------+

Teacher_Student (Junction Table): +-----------+-----------+ | TeacherID | StudentID | +-----------+-----------+ | 1 | 1 | | 1 | 2 | | 2 | 1 | +-----------+-----------+

What I want is to select only the TeacherID which has a record linking it with both StudentID 1 and StudentID 2. In this case, that would give me only TeacherID 1.

I have already tried the following SQL statement:

SELECT t_s.*
FROM Teacher_Student AS t_s
WHERE StudentID IN (1, 2)

And this returns me any records that have a StudentID of either 1 or 2. I have searched for answer but have been unable to find anything which has helped me so far, so asking as a last resort.

Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire