MySQL日记4: 自,左外,右外连接 + 找到每个员工的BOSS
案例:
有一张雇员表:
mysql> select * from emp;
+-------+--------+-----------+------+------------+---------+---------+--------+
| EMPNO | ENAME | JOB | BOSS | HIREDATE | SAL | COMM | DEPTNO |
+-------+--------+-----------+------+------------+---------+---------+--------+
| 7369 | SMITH | CLERK | 7902 | 1980-12-17 | 800.00 | NULL | 20 |
| 7499 | ALLEN | SALESMAN | 7698 | 1981-02-20 | 1600.00 | 300.00 | 30 |
| 7521 | WARD | SALESMAN | 7698 | 1981-02-22 | 1250.00 | 500.00 | 30 |
| 7566 | JONES | MANAGER | 7839 | 1981-04-02 | 2975.00 | NULL | 20 |
| 7654 | MARTIN | SALESMAN | 7698 | 1981-09-28 | 1250.00 | 1400.00 | 30 |
| 7698 | BLAKE | MANAGER | 7839 | 1981-05-01 | 2850.00 | NULL | 30 |
| 7782 | CLARK | MANAGER | 7839 | 1981-06-09 | 2450.00 | NULL | 10 |
| 7788 | SCOTT | ANALYST | 7566 | 1987-04-19 | 3000.00 | NULL | 20 |
| 7839 | KING | PRESIDENT | NULL | 1981-11-17 | 5000.00 | NULL | 10 |
| 7844 | TURNER | SALESMAN | 7698 | 1981-09-08 | 1500.00 | 0.00 | 30 |
| 7876 | ADAMS | CLERK | 7788 | 1987-05-23 | 1100.00 | NULL | 20 |
| 7900 | JAMES | CLERK | 7698 | 1981-12-03 | 950.00 | NULL | 30 |
| 7902 | FORD | ANALYST | 7566 | 1981-12-03 | 3000.00 | NULL | 20 |
| 7934 | MILLER | CLERK | 7782 | 1982-01-23 | 1300.00 | NULL | 10 |
+-------+--------+-----------+------+------------+---------+---------+--------+
14 rows in set (0.01 sec)
查询员工的上级领导,要求显示员工名和对应的领导名?
select
a.ename as '员工名', b.ename as '领导名'
from
emp a
join
emp b
on
a.boss = 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 |
+--------+--------+
13条记录,没有KING。《内连接》
上面的例子用左外,发现多了一条:KING NULL
select
a.ename as '员工名', b.ename as '领导名'
from
emp a
left join
emp b
on
a.mgr = b.empno;
+--------+--------+
| 员工名 | 领导名 |
+--------+--------+
| SMITH | FORD |
| ALLEN | BLAKE |
| WARD | BLAKE |
| JONES | KING |
| MARTIN | BLAKE |
| BLAKE | KING |
| CLARK | KING |
| SCOTT | JONES |
| KING | NULL |
| TURNER | BLAKE |
| ADAMS | SCOTT |
| JAMES | BLAKE |
| FORD | JONES |
| MILLER | CLARK |
+--------+--------+
如果用右外:会出现很多数据,比如 NULL | ALLEN
因为把老板表变成主表,会有一些老板没有下属(他们自己是最底层的).
这是不合理的
select
a.ename as empname, b.ename as bossname
from
emp a
right join
emp b
on
a.mgr = b.empno;
+---------+----------+
| empname | bossname |
+---------+----------+
| NULL | ADAMS |
| NULL | ALLEN |
| ALLEN | BLAKE |
| WARD | BLAKE |
| MARTIN | BLAKE |
| TURNER | BLAKE |
| JAMES | BLAKE |
| MILLER | CLARK |
| SMITH | FORD |
| NULL | JAMES |
| SCOTT | JONES |
| FORD | JONES |
| JONES | KING |
| BLAKE | KING |
| CLARK | KING |
| NULL | MARTIN |
| NULL | MILLER |
| ADAMS | SCOTT |
| NULL | SMITH |
| NULL | TURNER |
| NULL | WARD |
+---------+----------+
21 rows in set (0.00 sec)
所以,在求找到每个员工和其对应的领导的问题上,只需要单纯的用JOIN自连接即可。