SQL 查询查找不存在于其他表中的记录

SQL query find records that not persists in other tables

我需要打印所有不是学生而不是老师的人。我有三张桌子。甲骨文数据库。到目前为止的代码:

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;

我想我的查询是错误的,因为它 returns 0 个结果。您知道我必须更改什么吗?

使用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);

虽然你可以用left join来写这个查询,但我认为使用not exists的版本几乎是问题的直接翻译,更容易理解。

在 Oracle 中,您也可以使用 minus 编写此代码——如果您只需要 id:

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

" my query is wrong because it returns 0 results"

内连接 return 匹配时记录。您正在尝试查找既不加入 STUDENT 也不加入 TEACHER 的 PERSON 记录。因此,将您的查询更改为使用外部联接:

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;

这是一个反连接:return来自 PERSON 的记录与 STUDENT 和 TEACHER 中的记录不匹配。

--尝试使用左外连接...

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