如何在连接三个表时以更少的行获取所有信息?

时间:2018-02-24 02:47:26

标签: sql oracle

有人可以帮助我编写Oracle SQL Query以用于以下场景:

  1. 公司可以有多个部门。
  2. 每个部门都可以有多名员工。
  3. 员工不需要分配部门,但必须是公司ID。
  4. 这是我正在尝试的输出:

    enter image description here

    这是我到目前为止所尝试的查询:

    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;
    

    但它给出了这个输出:

    enter image description here

    修改

    Sql fiddle:http://sqlfiddle.com/#!4/df238/3/0

1 个答案:

答案 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;

Demo