MySQL,单表多列

时间:2014-03-08 19:31:30

标签: mysql sql

我有一个有这种结构的员工:

ID | firstName | lastName | reportsTo | jobTitle |
--------------------------------------------------

我想做一个查询,它会显示我的firstName,员工的lastName以及他/她向哪个员工报告(在此栏中,它包含员工的ID)。

表数据的例子:

ID | firstName | lastName | reportsTo | jobTitle   |
----------------------------------------------------
35 | John      | Green    | 36        | TeamLeader |
----------------------------------------------------
36 | Annie     | Red      | null        | Supervisor |
----------------------------------------------------

John Green的身份证号为35,他向Annie Red报道。如何在查询中执行此操作?

到目前为止,我已经基本上来了:

SELECT ID, firstName, lastName from employees;

由于

3 个答案:

答案 0 :(得分:2)

尝试使用子查询

SELECT ID, firstName, lastName,
( 
    SELECT a.firstName
    FROM employees a
    WHERE a.ID = reportsTo
) as report
from employees;

答案 1 :(得分:0)

SELECT e.ID, e.firstName, e.lastName,ee.firstName, ee.lastName from employees e
JOIN employees ee
ON e.reportsTo=ee.ID

员工的姓名和他向其汇报的姓名。

答案 2 :(得分:0)

使用

SELECT A.firstName, A.lastName, B.firstName 'reports to first name', 
B.lastName 'reports to last name'
from employees A JOIN employees B
ON B.ID = A.reportsTo

您可以在此处查看http://sqlfiddle.com/#!2/22e33f/3