How do I get rows not represented in many-to-many relationship?
I have a many-to-many relationship between students and classes as shown below. I would like to get the IDs of all the students who 开发者_开发问答are not registered for any classes.
Because of the size of the dataset, I'd like to avoid using NOT IN. Is there a more efficient solution?
NOT EXISTS should give you the best performance. See Left outer join vs NOT EXISTS for more details.
SELECT s.StudentID
FROM student s
WHERE NOT EXISTS(SELECT NULL
FROM student_class sc
WHERE sc.StudentID = s.StudentID)
select * from student
left join student_class on student_class.studentid = student.studentid
where student_class.scid is null;
An alternative is to use a left join:
SELECT s.student_id
FROM student s
LEFT JOIN student_class sc ON (sc.student_id = s.student_id)
WHERE sc.student_id IS NULL
The follwoing join query might result the answer
SELECT student.id
FROM student
LEFT JOIN student_class ON student.studentid = student_class.studentid
WHERE student_class.studentid IS NULL
You could also use
SELECT StudentID
FROM student
EXCEPT
SELECT StudentID
FROM student_class
精彩评论