数据库
首页 > 数据库> > mysql自连接

mysql自连接

作者:互联网

自连接:最大的特点是:一猴子那个表看做两张表,自己连自己。

案例:找出每个员工的上级领导,要求显示员工名和对应的领导名。

下面是原始数据(可以是员工表也可以是领导表):

mysql> select empno,ename,mgr from emp;
+-------+--------+------+
| 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 |
+-------+--------+------+

员工的领导编号 = 领导的员工编号

mysql> select e.ename as '员工名',b.ename'领导名' from emp e inner join emp b on e.mgr = b.empno;
+--------+--------+
| 员工名 | 领导名 |
+--------+--------+
| SMITH  | FORD   |
| ALLEN  | BLAKE  |
| WARD   | BLAKE  |
| JONES  | KING   |
| MARTIN | BLAKE  |
| BLAKE  | KING   |
| CLARK  | KING   |
| SCOTT  | JONES  |
| TURNER | BLAKE  |
| ADAMS  | SCOTT  |
| JAMES  | BLAKE  |
| FORD   | JONES  |
| MILLER | CLARK  |
+--------+--------+

标签:JONES,ename,BLAKE,员工,7839,mysql,7698,连接
来源: https://blog.csdn.net/qq_45148387/article/details/116324054