有人可以帮助我编写Oracle SQL Query以用于以下场景:
这是我正在尝试的输出:
这是我到目前为止所尝试的查询:
SELECT C.id Company_Id,
C.name Company_Name,
D.id Department_Id,
D.name Department_Name,
E.id Employee_Id,
E.name Employee_Name
FROM Company C
FULL OUTER JOIN Department D
ON D.CompanyId = C.Id
FULL OUTER JOIN Employee E
ON E.CompanyId = C.Id AND E.DepartmentId = D.Id
ORDER BY Company_Id,Department_Id,Employee_Id;
但它给出了这个输出:
修改
Sql fiddle:http://sqlfiddle.com/#!4/df238/3/0
答案 0 :(得分:3)
诀窍是将ON E.CompanyId = C.Id AND E.DepartmentId = D.Id
加入条件转换为
ON E.CompanyId = C.Id AND ( E.DepartmentId = D.Id OR E.DepartmentId is null )
SELECT C.id Company_Id,
C.name Company_Name,
D.id Department_Id,
D.name Department_Name,
E.id Employee_Id,
E.name Employee_Name
FROM Company C
FULL OUTER JOIN Department D
ON D.CompanyId = C.Id
FULL OUTER JOIN Employee E
ON E.CompanyId = C.Id AND ( E.DepartmentId = D.Id OR E.DepartmentId is null )
ORDER BY Company_Id,Department_Id,Employee_Id;