如何获取名称和管理器名称

zi8p0yeb  于 2021-06-17  发布在  Mysql
关注(0)|答案(3)|浏览(319)

如何获取姓名和经理姓名

+----+-----------+---------+
| 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 |
+-----------+-----------+
ru9i0ody

ru9i0ody1#

你可以自己加入 id 上的列 manager 列:

SELECT    e.name AS name, m.name AS manager
FROM      employee e
LEFT JOIN employee m ON m.id = e.manager
bpzcxfmw

bpzcxfmw2#

应该使用alias两次使用同一个表

select a.name, b.name as manager 
from my_table a 
left join  my_table b on a.manager  = b.id
mpbci0fu

mpbci0fu3#

看看这个

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;

相关问题