0

I am having three tables which has primary keys and references. I need to select the rows in below way. Please any one help me.

Table: Class (ClassId -> primarykey)

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

Table: Department(DeptId -> primarykey)

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

Table: ClassAndDepartment

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

Now I need to select the rows where the value exists in the table Class but does not exist in ClassAndDepartment

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Karthik Kumar
  • 13
  • 1
  • 1
  • 3

3 Answers3

3
select * from Class c where ClassId not in (select distinct ClassId from ClassAndDepartment)
xfx
  • 1,918
  • 1
  • 19
  • 25
1
select * 
from class c 
where classid not in (select classid from classanddepartment)
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
0

An alternative way to solve this is using a LEFT JOIN instead of NOT IN:

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

Avoiding NOT IN will usually improve performance.

Timothy
  • 469
  • 5
  • 8