从sql中的两个表中选择行

时间:2012-10-19 10:29:23

标签: sql join table-relationships

我有三个包含主键和引用的表。我需要以下面的方式选择行。请任何人帮助我。

表:ClassId -> primarykey

ClassId  ClassTitle
--------------------
1        First  
2        Second
3        Third

表:部门DeptId -> primarykey

DeptId   DeptName
-------------------
1        science
2        maths
3        general knowledge

表: ClassAndDepartment

ClassId  DeptId(ClassId-> foreign key of class and DeptId->foreign key of Department)
1        1
1        2
2        1
2        3

现在我需要选择表格Class中存在值的行,但ClassAndDepartment

中不存在

3 个答案:

答案 0 :(得分:3)

select * from Class c where ClassId not in (select distinct ClassId from ClassAndDepartment)

答案 1 :(得分:1)

select * 
from class c 
where classid not in (select classid from classanddepartment)

答案 2 :(得分:0)

另一种解决方法是使用LEFT JOIN代替NOT IN

SELECT *
FROM Class C
LEFT JOIN ClassAndDepartment CandD ON C.ClassId = CandD.ClassId
WHERE CandD.DeptId IS NULL

避免NOT IN通常会提高效果。