gpt4 book ai didi

mysql - 如何获取特定列未链接到另一个表的特定值的数据库表条目?

转载 作者:行者123 更新时间:2023-11-29 07:20:30 26 4
gpt4 key购买 nike

我有一个包含下表的数据库:Students、Classes、link_student_class。其中 Students 包含有关注册学生的信息,而 classes 包含有关类(class)的信息。由于每个学生可以参加多个类(class),每个类(class)可以有多个学生参加,所以我添加了一个链接表,用于学生和类(class)之间的映射。

链接表

id | student_id | class_id
1 1 1
2 1 2
3 2 1
4 3 3

在此表中,student_id 和 class_id 都会出现多次!我正在寻找的是一个 SQL 查询,它返回所有未参加特定类(class)(由其 id 给出)的学生的信息(如“SELECT * FROM students”)。

我尝试了以下 SQL 查询

SELECT * FROM `students` 
LEFT JOIN(
SELECT * FROM link_student_class
WHERE class_id = $class_id
)
link_student_class ON link_student_class.student_id = students.student_id

其中 $class_id 是我要排除的学生的类(class) ID。

在返回的对象中,我想包括的学生和我想排除的学生在“class_id”列的值上有所不同。那些要包含的值具有“NULL”,而那些我想排除的值具有数值。

最佳答案

NOT EXISTS 浮现在脑海中:

select s.*
from students s
where not exists (select 1
from link_student_class lsc
where lsc.student_id = s.student_id and
lsc.class_id = ?
);

? 是提供类的参数的占位符。

关于mysql - 如何获取特定列未链接到另一个表的特定值的数据库表条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56566674/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com