仅当值不在另一个表中时,选择查询才能从表列中获取值

时间:2013-09-16 14:03:58

标签: sql sql-server sql-server-2008-r2

如果只有值不在另一个表中,请有人建议我使用SQL Server Select查询从表列中获取值,这就是我想要做的事情:

SELECT t.TeacherID
FROM Teacher t ...... (Who are not in Class c, c.TeacherID Column)

3 个答案:

答案 0 :(得分:3)

select teacherID from Teacher
Except
select teacherID from Class

或者您也可以选择:

select teacherID from Teacher where TeacherId not in(select teacherID from Class)

答案 1 :(得分:1)

的教师有课程:

SELECT *
FROM   teacher
WHERE  NOT EXISTS (
         SELECT *
         FROM   class
         WHERE  class.teacherid = teacher.teacherid
       )

如果您想要反向(查找 的教师有课程),那么您所要做的就是扭转条件:删除NOT

答案 2 :(得分:0)

你也可以使用LEFT JOIN WHERE没有为教师iD分配课程

`SELECT teacher.ID `
`FROM   teacher LEFT JOIN Class ON teacher.ID =  Class.ID`
`WHERE   Class.ID IS NOT NULL`