简体   繁体   English

SQL 查询多对多关系

[英]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我编写了一个查询脚本来获取与给定学生 ID 对应的学生注册的课程,这样

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.但是,我正在努力查询具有给定学生 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 = ?
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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