我有一个表comments
,其中包含一个字段student_id
(students
表的外键。
我有另一张桌子students
我想做的是运行查询,显示所有未发表评论的学生。我有的SQL,只显示已发表评论的学生
SELECT studentID, email, first_name, last_name FROM "students" JOIN comments ON students.id = comments.student_id
如何“反向”此SQL以显示尚未评论的学生?
答案 0 :(得分:4)
一种方法使用not exists
:
select s.*
from students s
where not exists (select 1
from comments c
where s.id = c.student_id
);
答案 1 :(得分:1)
你可以这样做:
SELECT studentID, email, first_name, last_name
FROM students
LEFT JOIN comments ON students.id = comments.student_id
WHERE comments.student_id IS NULL
答案 2 :(得分:1)
select s.studentID, s.email, s.first_name, s.last_name from students s where s.id not in (select student_id from comments);