这是我最近在采访中被问到的一个问题:
您在组织中有各种类型的用户:Junior
(被领导) Supervisor
(被领导)Manager
(被领导通过)CEO
。
我们就这个单一的简化表架构达成一致。用户:{userId, userName, UserType(J, S, M, C), bossUserId}
问:编写一个查询以确定 userId = 11 的 初级
员工的完整组织层次结构。
示例数据:
答案是 => PQR2 --> GHI2 --> DEF1 --> ABC1
这是我的解决方案:
select e1.userName, e2.userName, e3.userName, e4.userName from
abc e1 inner join users e2 on e1.bossUserId = e2.userId
inner join users e3 on e2.bossUserId = e3.userId
inner join users e4 on e3.bossUserId = e4.userId
where e1.userId = 11;
我确实意识到 self 加入 4 次很糟糕,但我想不出其他任何事情。面试官告诉我有更好的方法,数据会按columnwise
显示。 (如果有的话,最多使用 2 个自连接
)
另一种可能性是编写存储过程,但同样不是单个查询。
谁能帮我解决这个问题?
最佳答案
根据您的评论,您可以在 MS SQL(以及其他类似的)中执行此操作
;with cte as (
select *, 0 as level from yourtable
union all
select cte.id, t2.name, t2.ut, t2.bossid, level+1
from cte
inner join yourtable t2 on cte.bossid = t2.id
)
select name, ut from cte
where id=11
order by level
这给了你
pqr2 j
ghi2 s
def1 m
abc1 c
但是 MySQL 不支持这种结构。
关于mysql - 使用单个查询确定用户的组织层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13607221/