Question

I have three related tables (students, classes, enrollments) (one student can have multiple enrollments and one class can have multiple enrollments) from which I need to select all students that are enrolled in classes (x,y,z) but not in classes (a, b, c). How can I structure my query to achieve this?

Was it helpful?

Solution

I don't agree that we need more information to be honest. Something like this should work. Another way would be two queries and using the MINUS keyword to get all results from the first query (students in classes x, y and z), except the results from the second query (students in classes a, b and c).

Selecting all students that are in ALL of classes x, y and z, and in NONE of classes a, b and c.

SELECT * FROM Students s
WHERE EXISTS (SELECT * FROM Enrollment
    WHERE studentId = s.StudentId AND ClassId = 'x')
AND EXISTS (SELECT * FROM Enrollment
    WHERE studentId = s.StudentId AND ClassId = 'y')
AND EXISTS (SELECT * FROM Enrollment
    WHERE studentId = s.StudentId AND ClassId = 'z')
AND NOT EXISTS (SELECT * FROM Enrollment
    WHERE studentId = s.StudentId AND ClassId IN ('a', 'b', 'c')

OTHER TIPS

Supposed DDL (just to introduce names):

create table student ( s_id numeric, name varchar );
create table class ( c_id numeric, name varchar );
create table enrollment ( s_id numeric, c_id numeric );
  1. Select ids of students not in a, b or c

    select s_id from enrollments where c_id not in
        (select c_id from class where name in ('a', 'b', 'c');
    
  2. Select ids of students in x, y or z

    select s_id from enrollments where c_id in
        (select c_id from class where name in ('x', 'y', 'z');
    
  3. Combine it

    select * from students where
        s_id in (select s_id from enrollments where c_id in
            (select c_id from class where name in ('x', 'y', 'z') and
        s_id not in (select s_id from enrollments where c_id in
            (select c_id from class where name in ('a', 'b', 'c');
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top