我必须收集最顶级父母的所有父母。 我的用户表格包含以下列
uid,supervisoruid
如果给定的uid是主管,我必须收集它的所有团队成员。 并且团队成员本身也是一些用户的主管。
我的下图是我需要的数据(我必须得到绿色的Uid)。
我尝试了下面的查询,它不适用于我
SELECT * FROM users u where u.uid in
(select distinct uid from users where supervisoruid='100'
or uid='100') and u.uid in u.supervisoruid
图形部门仅为3个。
示例数据
输入 100
输出 100101103
答案 0 :(得分:1)
您可以使用自我加入来查找100个孩子,他们有一个或多个自己的子记录。
示例数据
-- Sample data taken from OP.
DECLARE @User TABLE
(
[UID] INT PRIMARY KEY,
supervisorUID INT
)
;
INSERT INTO @User
(
[UID],
supervisorUID
)
VALUES
(100, 100),
(101, 100),
(102, 100),
(103, 100),
(104, 100),
(105, 101),
(106, 101),
(107, 101),
(108, 103),
(109, 103),
(110, 103)
;
<强>查询强>
/* Self join returns any records with a supervisorUID of 100
* and 1 or more children.
*/
SELECT
parent.[UID]
FROM
@User AS parent
INNER JOIN @User AS child ON child.supervisorUID = parent.[UID]
WHERE
parent.supervisorUID = 100
GROUP BY
parent.[UID]
;
过滤父表的supervisorUID为100会返回记录100,101,102,103和104.自联接会删除102和104,因为它们不会出现在任何记录的supervisorUID列中。
如果您的图表超过三个级别,此技术将会中断。
答案 1 :(得分:0)
您也可以使用递归SQL:
-- Sample data taken from OP.
DECLARE @User TABLE
(
[UID] INT PRIMARY KEY,
supervisorUID INT
)
;
INSERT INTO @User
(
[UID],
supervisorUID
)
VALUES
(100, 200),
(101, 100),
(102, 100),
(103, 100),
(104, 100),
(105, 101),
(106, 101),
(107, 101),
(108, 103),
(109, 103),
(110, 103)
;
递归SQL查询
with Recursivetable (Supervisoruid, uid, level)
as
(
-- anchor point
select e.supervisoruid, e.uid,
0 as level
from @User as e
where e.supervisoruid = '200'
union all
select e.supervisoruid, e.uid,
LEVEL + 1
from @User as e
inner join Recursivetable as d
on e.supervisorUID = d.uid
)
select distinct Supervisoruid
/* remove distinct and and below comment-- for entire tree */
--, uid, level
from Recursivetable
go