我有三个包含主键和引用的表。我需要以下面的方式选择行。请任何人帮助我。
表:类(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
答案 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
通常会提高效果。