如何显示两个相对表的数据?

How can I show the data of two opposite tables?

我有下表,其中插入了一些信息。这是一个例子:

Table 人

id_person       name
--------------------------
   1            name1
   2            name2
   3            name3
   4            name4
   5            name5
   6            name6

Table教授

id_professor (references id_person)
------------
     1
     2
     5
     6

Table学生

id_student (references id_person)
----------
    1
    3
    4
    5

我想执行一个 select 来显示所有表中的几乎所有数据,但只显示来自学生或教授的那些人。所以我想要得到的输出,给定这个例子是:

 name        id_professor      id_student      
-------------------------------------------
 name2           2                NULL
 name3          NULL               3
 name4          NULL               4
 name6           6                NULL

我该怎么做?

我试过执行此查询但没有成功:

select p.name, s.id_student, pr.id_professor from 
person p inner join student s on p.id_person = s.id_student right join professor r on s.id_student = pr.id_professor
where (s.id_student is null) or (pr.id_professor is null);

您可以使用两个 left join 和一些过滤:

select p.name, pr.id_professor, s.id_student
from person p left join
     professor pr
     on pr.id_professor = p.id_person left join
     student s
     on s.id_student = p.id_person
where (pr.id_professor is not null and s.id_student is null) or
      (pr.id_professor is null and s.id_student is not null);

此查询将为您提供所有人或教授或两者兼而有之的人

select p.name, pr.id_professor, s.id_student
from person p 
left join professor pr on pr.id_professor = p.id_person 
left join student s on s.id_student = p.id_person
where s.id_student is not null or pr.id_professor is not null