Note: The test database version is MySQL 8.0
If you need scott users to create tables and enter data statements, please refer to:
scott create tables and enter data sql scripts
1. Demand
Employee CLARK works for KING, suppose employee CLARK is another employee's manager, what should I do?
select ename,empno,mgr
from emp
where ename in (‘KING’,‘CLARK’,‘MILLER’);
±-------±------±-----+
| ename | empno | mgr |
±-------±------±-----+
| CLARK | 7782 | 7839 |
| KING | 7839 | NULL |
| MILLER | 7934 | 7782 |
±-------±------±-----+
It can be seen that the employee MILLER works for CLARK, and CLARK works for KING.
Now it is necessary to express the complete hierarchy from MILLER to KING.
The following result set is returned:
±----------------------+
| leaf_branch_root |
±----------------- -----+
| MILLER–>CLARK–>KING |
±----------------------+
2. Solution
Perform two self-joins on the table EMP and return to MILLER, CLARK, the manager of MILLER, and KING, the manager of CLARK.
select concat(a.ename,'-->',b.ename,'-->',c.ename) as leaf_branch_root
from emp a, emp b, emp c
where a.ename = 'MILLER'
and a.mgr = b.empno
and b.mgr = c.empno;
Test Record:
mysql> select concat(a.ename,'-->',b.ename,'-->',c.ename) as leaf_branch_root
-> from emp a, emp b, emp c
-> where a.ename = 'MILLER'
-> and a.mgr = b.empno
-> and b.mgr = c.empno;
+-----------------------+
| leaf_branch_root |
+-----------------------+
| MILLER-->CLARK-->KING |
+-----------------------+
1 row in set (0.00 sec)