查询时有没有办法替换列值?

时间:2013-04-15 08:16:11

标签: mysql sql

我有一张存储员工信息的表格:

mysql> select * from emp;

+-------+--------+-----------+------+------------+---------+---------+--------+
| EMPNO | ENAME  | JOB       | MGR  | 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 | 1982-09-12 | 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 | 1983-01-12 | 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.24 sec)

有一个名为MGR的专栏,说明每个员工的老板是谁(好吧,老板'EMPNO)。
我想要的是提出一个查询,向我展示我的所有员工和他们的老板的名字,而不是身份证 结果表格如下所示:

+-------+----------+
| ENAME | BOSSNAME |
+-------+----------+
| SMITH |   FORD   |
| ALLEN |   BLAKE  |
|  etc. |    etc.  |
+-------+----------+

有没有办法完成任务? 请注意,没有第二个名为BOSSES的表,或类似的东西。每个员工都存储在同一个表中。

1 个答案:

答案 0 :(得分:7)

您需要使用LEFT JOIN自行加入表格,因此所有没有MGR的员工仍会显示在列表中

SELECT  a.Ename EmpName,
        b.Ename BossName
FROM    emp a
        LEFT JOIN emp b
            ON a.MGR = b.EmpNo

要进一步了解联接,请访问以下链接:

输出

╔═════════╦══════════╗
║ EMPNAME ║ BOSSNAME ║
╠═════════╬══════════╣
║ SCOTT   ║ JONES    ║
║ FORD    ║ JONES    ║
║ ALLEN   ║ BLAKE    ║
║ WARD    ║ BLAKE    ║
║ MARTIN  ║ BLAKE    ║
║ TURNER  ║ BLAKE    ║
║ JAMES   ║ BLAKE    ║
║ MILLER  ║ CLARK    ║
║ ADAMS   ║ SCOTT    ║
║ JONES   ║ KING     ║
║ BLAKE   ║ KING     ║
║ CLARK   ║ KING     ║
║ SMITH   ║ FORD     ║
║ KING    ║ (null)   ║
╚═════════╩══════════╝