如何获取姓名和经理姓名
+----+-----------+---------+
| id | name | manager |
+----+-----------+---------+
| 1 | bhupendra | 0 |
| 2 | shyam | 1 |
| 3 | ram | 1 |
| 4 | geeta | 2 |
| 5 | sita | 1 |
+----+-----------+---------+
我需要
之类的结果+-----------+-----------+
| name | manager |
+-----------+-----------+
| bhupendra | |
| shyam | bhupendra |
| ram | bhupendra |
| geeta | shyam |
| sita | bhupendra |
+-----------+-----------+
答案 0 :(得分:1)
您可以自行加入id
列上的manager
列:
SELECT e.name AS name, m.name AS manager
FROM employee e
LEFT JOIN employee m ON m.id = e.manager
答案 1 :(得分:0)
检查一下
with recursive cte (id, name, parent_id) as (
select id,
name,
manager
from employee
union all
select p.id,
p.name,
p.manager
from employee e
inner join cte
on p.manager = cte.id
)
select * from cte;
答案 2 :(得分:0)
您应该使用别名两次使用同一张表
select a.name, b.name as manager
from my_table a
left join my_table b on a.manager = b.id