加入与父母和祖父母的关系

时间:2021-02-17 10:49:08

标签: sql hierarchical-query

给定关系:

Teacher -> Students -> Advisors

也可以

Teacher -> Advisors

如果顾问的 FK 指向老师而不是学生,我该如何编写一个 join 语句来显示学生的空值?不用写两个单独的 select 语句?

截至目前,我的查询如下所示:

SELECT 
    t.teacherId, t.name,
    s.studentId, s.name,
    a.advisorId, a.name,
FROM
    teacher t 
JOIN
    student s ON t.teacherId = s.teacherId
JOIN 
    advisor ON s.studentId = a.personId

编辑:基本上我希望下面的查询结果与上面的结果相结合。但是因为某些 FK 缺少中间(学生)的连接,我希望它们显示为 null

SELECT 
    t.teacherId, t.name,
    a.advisorId, a.name,
FROM
    teacher t 
JOIN
    advisor ON s.teacherId = a.personId

2 个答案:

答案 0 :(得分:1)

使用union all

SELECT t.teacherId, t.name,
       s.studentId, s.name,
       a.advisorId, a.name
FROM teacher t JOIN
     student s
     ON t.teacherId = s.teacherId JOIN
     advisor a
     ON s.studentId = a.personId
UNION ALL
SELECT t.teacherId, t.name,
       NULL, NULL,
       a.advisorId, a.name
FROM teacher t JOIN
     advisor
     ON s.teacherId = a.personId

答案 1 :(得分:1)

使用联合所有:

SELECT t.teacherId, t.name,
       s.studentId, s.name,
       a.advisorId, a.name,
FROM teacher t 
JOIN student s
  ON t.teacherId = s.teacherId
JOIN advisor
  ON s.studentId = a.personId
UNION ALL
SELECT t.teacherId, t.name,
       null, null, 
       a.advisorId, a.name,
FROM teacher t 
JOIN advisor
  ON s.teacherId = a.personId