假设我有表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 | +--------------+--------+
答案 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