0

我有一个包含员工及其直属经理的目录表。我正在尝试遍历报告层次结构,以便在必要时让每个人都回到报告线 - 当你打到没有经理的人(即首席执行官)时,你可以停下来。而不是循环通过一堆 PHP if/else 语句,我试图在一个 MySQL 查询中完成它。

迄今为止的最大努力是:

SELECT d1.empno AS d1, d2.empno AS d2, d3.empno AS d3, d4.empno AS d4, d5.empno AS d5, d7.empno AS d7, d8.empno AS d8
FROM `directory` AS d1
LEFT JOIN directory AS d2 ON d1.manageremp = d2.empno
LEFT JOIN directory AS d3 ON d2.manageremp = d3.empno
LEFT JOIN directory AS d4 ON d3.manageremp = d4.empno
LEFT JOIN directory AS d5 ON d4.manageremp = d5.empno
LEFT JOIN directory AS d6 ON d5.manageremp = d6.empno
LEFT JOIN directory AS d7 ON d6.manageremp = d7.empno
LEFT JOIN directory AS d8 ON d7.manageremp = d8.empno
WHERE d1.empno = '38414'

但这会返回所有八个结果,无论是否有必要。因此,如果我要检索比 CEO 低两级的人的层次结构,我会得到

d1     d2     d3    d4   d5   d6   d7   d8
13307  55192  10917 NULL NULL NULL NULL NULL

而我真的只想得到这个:

d1     d2     d3
13307  55192  10917

因此,如果前一个 manageremp 不是 NULL,我只想选择下一个 empno。但是这样的东西似乎不起作用:

SELECT d1.empno AS d1, 
CASE 
WHEN d1.manageremp IS NOT NULL THEN d2.empno END AS d2, 
CASE 
WHEN d2.manageremp IS NOT NULL THEN d3.empno END AS d3,
CASE 
WHEN d3.manageremp IS NOT NULL THEN d4.empno END AS d4,
...

我确信有一个优雅的解决方案,但我没有看到它。有任何想法吗?

4

0 回答 0