Transact SQL - 使用NOT EXISTS子句而不是NOT IN

时间:2016-03-11 19:45:31

标签: sql-server tsql

我正在尝试修改此Transact SQL语句以使用NOT EXISTS子句而不是NOT IN。我使用过搜索引擎,但我很难应用我找到的例子。

SELECT StudentId 
FROM Students 
WHERE School NOT IN (SELECT School FROM ClosedSchools) 

3 个答案:

答案 0 :(得分:0)

如果StudentsClosedSchools都有SchoolId字段:

SELECT StudentId 
FROM Students stu
WHERE NOT EXISTS (
    SELECT School 
    FROM ClosedSchools clo
    WHERE clo.SchoolId = stu.SchoolId);

答案 1 :(得分:0)

SELECT  StudentId
FROM    Students AS a
WHERE   NOT EXISTS ( SELECT School
                     FROM   ClosedSchools AS b
                     WHERE  a.School = b.School ) 

答案 2 :(得分:0)

SELECT s.StudentId 
  FROM Students s
 WHERE NOT EXISTS ( SELECT 1 
                      FROM ClosedSchools 
                     where ClosedSchools.School = s.School 
                  )

SELECT s.StudentId 
  FROM Students s
  LEFT JOIN ClosedSchools 
        on ClosedSchools.School = s.School 
 WHERE ClosedSchools.School is null;