条件选择

时间:2013-05-03 02:10:16

标签: mysql conditional-statements

我有一个包含员工及其直属经理的目录表。我试图在报告层次结构中循环,以便在必要时让每个人都返回报告行 - 当你遇到没有经理的人(即CEO)时,你就可以停止了。我没有遍历一堆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'

但无论是否有必要,都会返回所有八个结果。因此,如果我在首席执行官以下两步检索层次结构,我会得到

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

而我真的只想得到这个:

d1     d2     d3
13307  55192  10917

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

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,
...

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

0 个答案:

没有答案