mysql选择不是多对多关系的行

min*_*sky 4 php mysql sql

我有一个数据结构,学生和小组之间有多对多的关系.我有三张桌子

学生:身份证,姓名

组:id,name

students_groups:student_id,group_id

如何仅选择不在特定组中的学生(例如group.id = 1)?

我做了一些搜索并尝试使用子查询,但只获得一个空集......

select * from students where not exists (select students.* from students left join students_groups on students_groups.student_id = student.id where students_groups.group_id = 1);
Run Code Online (Sandbox Code Playgroud)

我该怎么查询?提前多了!

编辑 好了,似乎以下两个最终工作...任何人可以解释为什么我不需要加入表工作?

select * from students where not exists (select * from students_groups where students_groups.student_id = student.id and student_groups.group_id = 1);

select * from students where id not in (select student_id from students_groups where group_id = 1);
Run Code Online (Sandbox Code Playgroud)

Bor*_*ort 9

使用NOT IN应该工作正常:

SELECT * FROM Students
WHERE Id NOT IN (
    SELECT Student_Id FROM Students_Groups
    WHERE Group_Id = 1)
Run Code Online (Sandbox Code Playgroud)