Skip to content
Advertisement

How to select rows in a many-to-many relationship? (SQL)

I have a Students table and a Courses table. They have a many to many relationship between them and the StudentCourses table is the intermediary. Now, I have a list of Course ids and want to select the Students that follow all Courses in my list. How??

In this example, I only want the result to be John and Jane, because they both have the two courses in my CourseList. I dont want Donald, because he only has one of them.

Have tried this JOIN, construction, but it does not eliminate students that only have some of my desired courses.

Advertisement

Answer

If you want students with all your required courses, you can use aggregation and having:

If you want additional information about students, you can join in the Students table (or use a IN or a similar construct).

Note that this only needs the StudentCourses table. It has the matching ids. There is no need to join in the reference tables.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement