我有一张官方桌子,上面有id和名字......
官员可能有主管 - 这些主管存储在一个名为officialsupervisor的联接表中,其中包含official_id和supervisor_id作为官方表的外键。
我可以向他们的主管展示官员
SELECT o.official_name Official, p.official_name Supervisor
FROM officialsupervisor s, official o, official p
WHERE o.official_id = s.official_id AND p.official_id = s.supervisor_official_id
我可以列出没有主管的官员
SELECT o.official_name Official
FROM official o
WHERE o.official_id NOT IN (SELECT official_id
FROM officialsupervisor)
但我无法弄清楚如何将所有官员列入他们的主管,如果他们没有,那就是空白。我觉得这应该很简单!
感谢您的帮助。
答案 0 :(得分:4)
尝试一次:
SELECT o.official_name Official, p.official_name Supervisor
FROM official o
LEFT JOIN officialsupervisor s ON o.official_id = s.official_id
LEFT JOIN official p ON p.official_id = s.supervisor_official_id
答案 1 :(得分:3)
您不需要递归查询只需将OUTER JOINS
加入两个表:
SELECT o.official_name Official, p.officialname
FROM officialsupervisor s
Left Outer Join official o on o.official_id = s.official_id
Left Outer JOIN official p ON p.official_id = s.supervisor_official_id