Search code examples
sqljointable-relationships

Select rows from two tables in sql


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


Solution

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