Reputation: 148
How to get name and manager name
+----+-----------+---------+
| id | name | manager |
+----+-----------+---------+
| 1 | bhupendra | 0 |
| 2 | shyam | 1 |
| 3 | ram | 1 |
| 4 | geeta | 2 |
| 5 | sita | 1 |
+----+-----------+---------+
i need result like
+-----------+-----------+
| name | manager |
+-----------+-----------+
| bhupendra | |
| shyam | bhupendra |
| ram | bhupendra |
| geeta | shyam |
| sita | bhupendra |
+-----------+-----------+
Upvotes: 0
Views: 231
Reputation: 133380
You should use the same table twice using alias
select a.name, b.name as manager
from my_table a
left join my_table b on a.manager = b.id
Upvotes: 0
Reputation: 30625
Check this out
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;
Upvotes: 0
Reputation: 311808
You could self-join the id
column on the manager
column:
SELECT e.name AS name, m.name AS manager
FROM employee e
LEFT JOIN employee m ON m.id = e.manager
Upvotes: 1