当没有分配员工(1 级)时,如何将经理保持在 2 级?

How do I maintain manager at level 2 when no employees (level 1) assigned?

我有两个 table 用于员工经理关系。一个table是员工id,一个是父子link。我与父子 link table 一起多次加入员工 table,试图创建:高级经理(Lvl 1)、经理(Lvl 2)和员工(Lvl 3) ) 但是我 运行 遇到了经理的问题,经理没有分配给他们的员工。没有以 mgrid 作为源的目标记录。

我将如何创建一个空记录并使没有分配 employeeid 的经理保持在 2 级?

Table布局

EmpID table 作为开斋节

EmpID
123
456

ParentChild Table 作为 PC:

DestinationID (Child) SourceID (Parent)
456 123
789 123
111 789

加入

Select eid.empID (Level_3), pc.sourceid (level_2), pc2.sourceid (level_1)
   From empid as eid
    Left join parentchild as pc on eid.empID = pc.destinationID
     Left Join empid as eid2 on pc.sourceId = eid2.empid
      Left join parentchild as pc2 on eid2.empid = pc2.destinationID

预期结果:

Level_1 Level_2 Level_3
Null 456 123
111 789 123

没有员工的经理只出现在第 1 级,因为他们向 sr 经理报告,而不是第 2 级且有 1 级空记录。

Level_1 Level_2 Level_3
456 123 Null
111 789 123

对于 Oracle(如 Oracle 19c 等),您需要对 SQL 语法进行一些调整。我们只需要使用链接 table parentchild 来获取您需要的详细信息。

试试这个:

SELECT pc2.destinationid level_1, pc.destinationid level_2, pc.sourceid Level_3
  FROM      parentchild   pc
  LEFT JOIN parentchild   pc2   on pc2.sourceid  = pc.destinationid
 WHERE pc.sourceid = 123
;

结果:

+------+-----------+
|    1 |   2 |   3 |
+------+-----------+
|  111 | 789 | 123 |
| null | 456 | 123 |
+------+-----------+

Full working test case

注意:使用递归,我们不需要对树的每一层都使用显式连接,也不需要知道深度。 Oracle 有两种方法可以做到这一点:

  1. WITH clause - 常用 Table 表达式
  2. CONNECT BY - Oracle 特定语法