简体   繁体   中英

SQL query in many-to-many relationship

I am struggling a problem described bellow.

Suppose there is a many-to-many relationship between students and classes, and middle table who explains which student enrolled which classes like the image.

在此处输入图像描述

Referring from this site.

I wrote a query script to get classes enrolled by the student who is corresponding to the given student id, such that

select c.Title, 
       c.Description 
from Enrollments as e 
inner join Students s on e.Student_ID = s.id 
inner join Classes c on e.Class_ID = c.id where Student_ID = ?;

However, I am struggling a problem to query the classes not enrolled by the student with given student id.

Thanks.

I would use exists logic here:

SELECT c.Title, c.Description
FROM Classes c
WHERE NOT EXISTS (
    SELECT 1
    FROM Enrollments e
    WHERE e.Class_ID = c.id AND e.Student_ID = ?
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM