简体   繁体   中英

SQL query find records that not persists in other tables

I need to print all persons which are not students and not teachers. I have three tables. Oracle database. Code so far:

SELECT PersonID, FirstName, LastName, Gender, DateOfBirth
FROM PERSON 
INNER JOIN STUDENT S ON PERSON.PersonID = S.StudentID 
INNER JOIN TEACHER T ON PERSON.PersonID = T.TeacherID
WHERE PERSON.PersonID != S.StudentID
AND PERSON.PersonID != T.TeacherID;

I guess my query is wrong because it returns 0 results. Do you have any idea what must I change?

" my query is wrong because it returns 0 results"

Inner joins return records when there is a match. You're trying to find PERSON records which join to neither STUDENT nor TEACHER. So, change your query to use outer joins:

SELECT PersonID, FirstName, LastName, Gender, DateOfBirth
FROM PERSON 
LEFT OUTER JOIN STUDENT S ON PERSON.PersonID = S.StudentID 
LEFT OUTER JOIN TEACHER T ON PERSON.PersonID = T.TeacherID
WHERE S.StudentID is null
AND  T.TeacherID is null;

This is an anti-join: it returns records from PERSON which don't match records in STUDENT and TEACHER.

Use not exists :

select p.*
from person p
where not exists (select 1 from teacher t where t.teacherid = p.personid) and
      not exists (select 1 from students s where s.studentid = p.personid);

Although you can write this query with left join , I think the version using not exists is almost a direct translation of the question, making it easier to understand.

In Oracle, you can also write this using minus -- if you want only the id:

select personid
from person
minus
select teacherid
from teacher
minus
select studentid
from student;

--Try this with Left Outer Join...

SELECT
  P.PersonID, 
  P.FirstName, 
  P.LastName, 
  P.Gender, 
  P.DateOfBirth
FROM PERSON P
LEFT OUTER JOIN STUDENT S ON P.PersonID = S.StudentID 
LEFT OUTER JOIN TEACHER T ON P.PersonID = T.TeacherID
WHERE S.PersonID is null and T.PersonID is null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM