empno ename mgr
------ ------ --------
7369 SMITH 7902
7499 ALLEN 7698
7521 WARD 7698
7566 JONES 7839
7654 MARTIN 7698
7698 BLAKE 7839
7782 CLARK 7839
7788 SCOTT 7566
7839 KING (NULL)
7844 TURNER 7698
7876 ADAMS 7788
7900 JAMES 7698
7902 FORD 7566
7934 MILLER 7782
其中,mgr 为 NULL 表明该员工没有上级领导。
我们要把每个员工的所有上级领导都找出来,实现的效果如下:
empno ename path
------ ------ ----------------------
7369 SMITH ->FORD->JONES->KING
7499 ALLEN ->BLAKE->KING
7521 WARD ->BLAKE->KING
7566 JONES ->KING
7654 MARTIN ->BLAKE->KING
7698 BLAKE ->KING
7782 CLARK ->KING
7788 SCOTT ->JONES->KING
7839 KING
7844 TURNER ->BLAKE->KING
7876 ADAMS ->SCOTT->JONES->KING
7900 JAMES ->BLAKE->KING
7902 FORD ->JONES->KING
7934 MILLER ->CLARK->KING
SELECT
a.empno,
a.ename,
CONCAT(
IFNULL(CONCAT('->', b.ename), ''),
IFNULL(CONCAT('->', c.ename), ''),
IFNULL(CONCAT('->', d.ename), '')
) AS path
emp a
LEFT JOIN emp b
ON b.empno = a.mgr
LEFT JOIN emp c
ON c.empno = b.mgr
LEFT JOIN emp d
ON d.empno = c.mgr
WITH RECURSIVE leader_path(empno, ename, mgr, path) AS
(SELECT
empno,
ename,
CAST('' AS CHAR(100)) AS path
UNION ALL
SELECT
a.empno,
a.ename,
b.mgr,
CONCAT(
a.path,
IFNULL(CONCAT('->', b.ename), '')
leader_path a
LEFT JOIN emp b
ON a.mgr = b.empno
WHERE b.empno IS NOT NULL)
SELECT
empno,
ename,