我有一个SQL表worker
,其字段为:
1. id
2. Name
3. Manager id
我正在尝试编写查询以获取以下字段列表('id','name','manager id','manager name')
请注意,经理ID也属于工作人员,即经理也是工人。此外,经理还有一个经理,他再次属于同一个表 - 层次结构可以升级到n个经理(未知)。
到目前为止,这是我的查询
SELECT tab1.user_name, tab1.user_id, tab1.manager_id, tab2.name AS manager_name, 1 AS LEVEL FROM (SELECT tab1.name AS user_name, tab1.id AS user_id, manager_id FROM DB.user tab1 WHERE id = 1 AND active = 1) tab1 LEFT JOIN DB.user tab2 ON tab1.manager_id = tab2.id UNION SELECT tab1.user_name, tab1.user_id, tab1.manager_id, tab2.name AS manager_name, 2 AS LEVEL FROM (SELECT tab1.name AS user_name, tab1.id AS user_id, manager_id FROM DB.user tab1 WHERE manager_id = 1 AND active = 1) tab1 LEFT JOIN DB.user tab2 ON tab1.manager_id = tab2.id UNION SELECT tab1.user_name, tab1.user_id, tab1.manager_id, tab2.name AS manager_name,
3 AS LEVEL FROM (SELECT tab1.name AS user_name, tab1.id AS user_id, manager_id FROM DB.user tab1 WHERE manager_id IN (SELECT tab1.id FROM DB.user tab1 WHERE manager_id = 1 AND active = 1) AND active = 1 ) tab1 LEFT JOIN DB.user tab2 ON tab1.manager_id = tab2.id
但是这让我得到了结果,直到第3级的heirarchy,而我需要它自我扩展并且无论嵌套存在什么级别都可以获取结果。
有人可以帮忙吗。
答案 0 :(得分:1)
select w1.id, w1.name, w2.id as manager_id, w2.name as manager_name
from worker as w1 inner join worker w2 on w1.manager_id = w2.id