如何使用sql比较单个表中两行的两列值?

时间:2018-03-19 05:41:04

标签: sql mysqli

假设我有表employee

+--------------+--------+------------+
| id           | e_name |  leder_id  |
+--------------+--------+------------+
| 1            | abc    | 2          |
| 2            | def    | 4          |
| 3            | ghi    | 2          |
| 4            | jkl    | 1          |
| 5            | mno    | 3          |
+--------------+--------+------------+

...我希望通过SQL使用这样的输出。每个e_name都有一个领导者,他们的leder_id被给予。

+--------------+---------+
|e_name        | l_name | 
+--------------+--------+
| abc          | def    | 
| def          | jkl    | 
| ghi          | def    | 
| jkl          | abc    | 
| mno          | ghi    | 
+--------------+--------+

2 个答案:

答案 0 :(得分:4)

执行 SELF JOIN

SELECT 
       e.e_name, el.e_name as l_name 
FROM employee e
INNER JOIN employee el on el.id = e.leder_id    

如果某个员工没有任何领导者使用LEFT OUTER JOIN

答案 1 :(得分:2)

你走了:

SELECT
    e.e_name as e_name ,
    l.e_name as l_name        
FROM
    employee e,
    employee l
WHERE
    e.leder_id  = l.id