MySQL represents a parent-child relationship

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

Put the information of the parent record with the data in the record only. For example, display the name of each employee and the name of their manager.

返回的结果集:
±----------------------+
| emps_and_mgrs |
±----------------------+
| SMITH woks for FORD |
| ALLEN woks for BLAKE |
| WARD woks for BLAKE |
| JONES woks for KING |
| MARTIN woks for BLAKE |
| BLAKE woks for KING |
| CLARK woks for KING |
| SCOTT woks for JONES |
| TURNER woks for BLAKE |
| ADAMS woks for SCOTT |
| JAMES woks for BLAKE |
| FORD woks for JONES |
| MILLER woks for CLARK |
±----------------------+

2. Solution

Self-join the MGR and EMPNO to the EMP table and find the manager of each employee.
Then, according to the string connection function provided by MySQL, the required string in the result set is generated.

select  concat(a.ename, ' woks for ',b.ename) as emps_and_mgrs
  from  emp a, emp b
 where  a.mgr = b.empno;

Test Record:

mysql> select  concat(a.ename, ' woks for ',b.ename) as emps_and_mgrs
    ->   from  emp a, emp b
    ->  where  a.mgr = b.empno;
+-----------------------+
| emps_and_mgrs         |
+-----------------------+
| SMITH woks for FORD   |
| ALLEN woks for BLAKE  |
| WARD woks for BLAKE   |
| JONES woks for KING   |
| MARTIN woks for BLAKE |
| BLAKE woks for KING   |
| CLARK woks for KING   |
| SCOTT woks for JONES  |
| TURNER woks for BLAKE |
| ADAMS woks for SCOTT  |
| JAMES woks for BLAKE  |
| FORD woks for JONES   |
| MILLER woks for CLARK |
+-----------------------+
13 rows in set (0.00 sec)

Guess you like

Origin blog.csdn.net/u010520724/article/details/114021411