从多对多设计中选择记录

时间:2009-01-26 21:17:36

标签: sql tsql

有三个表,Student,Classes,Student_Class

是否可以选择未使用NOT IN在任何班级注册的学生?

e.g。从学生名单中选择学生姓名(从Student_Class中选择Distinct studentid)

3 个答案:

答案 0 :(得分:4)

我真的不知道为什么你不想使用NOT IN,但这是另外一个选择......

SELECT Studentname
FROM Students
LEFT JOIN Student_Class ON Student_Class.StudentID = Student.ID
WHERE Student_Class.StudentID IS NULL

答案 1 :(得分:3)

有三种方法:

  1. SELECT StudentName FROM Students WHERE StudentID NOT IN (SELECT StudentID FROM StudentClass);
  2. SELECT StudentName FROM Students s WHERE NOT EXISTS (SELECT StudentID FROM StudentClass WHERE StudentID = s.StudentID);和
  3. SELECT StudentName FROM Students s LEFT OUTER JOIN StudentClass sc ON s.StudentID = sc.StudentID WHERE sc.StudentID IS NULL)
  4. 我真的不会用(3)。所以选一个。

    WHERE EXISTS / WHERE NOT EXISTS通常首选IN / NOT IN。现代优化器可能会优化(1)和(2)在很多时候都是相同的。值得比较性能(当它重要时)。

答案 2 :(得分:0)

Select studentname from Students s Where s.studentid NOT EXISTS (Select 1 From Student_Class sc where sc.studentid = s.studentid)