MySQL recursive subquery [duplicate]

淺唱寂寞╮ 提交于 2019-12-11 14:48:24

问题


Not sure the title accurately reflects what I need to do and this question is possibly out of the scope of Stack Overflow as I do not have much to work with, other than my problem. I will explain my scenario ...

I have a reporting web application. There are three levels of users Senior Managers, Managers and Team Members. Each Manager is responsible for a team. Each Senior Manager is responsible for a subset of Managers.

Senior Managers and Managers write a report on their subordinates. Currently the system only allows Manager to view reports on their immediate subordinates. However the system is to be adapted to allow Senior Managers to view reports on their Managers as well as view any reports the Managers have written about their team members.

I have table team_members table which governs which team a user is in. So ...

Users
--------
uid
forename
surname

team_members
------------
id
leader_id
member_id

leader_id and member_id relate to the primary key of the users table; uid.

So as a Senior Manager I need to be able to generate a list of all immediate team members (Managers), plus a list of their subordinates. Is there a way to do this within one query?


回答1:


i'm not sure if herachial data is what you need/want, but here's what you need

all tops, middle, an regular members, DEMO, SQL :

select 
IFNULL((SELECT name FROM users where uid=smng.leader_id),(SELECT name FROM users where uid=mng.leader_id)) 
         as top, 
(SELECT name FROM users where uid = mng.leader_id) 
         as middle,
usr.name as regular
from 
 users usr inner join managers mng on usr.uid=mng.member_id 
    inner join managers smng on mng.leader_id = smng.member_id

for specified top manager add :

where smng.leader_id =1

for a specified middle manager change to :

where mng.leader_id =2


来源:https://stackoverflow.com/questions/19120384/mysql-recursive-subquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!