sql递归查找以及给有标识的用户分层级

本文介绍了一种使用SQL的WITH语句进行递归查询的方法,以解析分销商的层级结构,包括直接上级合伙人和间接上级合伙人的ID。通过递归联合的方式,实现了对分销商层级的深度遍历。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述加粗样式
WITH D(UserId,ReferralUserId,DistributorGradeId,LevelId,IsEnterprisePartner,UpEnterpriseUserId,UpTwoEnterpriseUserId,UpThreeEnterpriseUserId) AS(
SELECT UserId,ReferralUserId,DistributorGradeId,0 as LevelId,IsEnterprisePartner,(case IsEnterprisePartner when 1 then UserId else 0 end) UpEnterpriseUserId,0 as UpTwoEnterpriseUserId,0 as UpThreeEnterpriseUserId FROM aspnet_Distributors
WHERE UserId=38546
UNION ALL
SELECT a.UserId,a.ReferralUserId,a.DistributorGradeId,D.LevelId + 1 as LevelId,a.IsEnterprisePartner,
(case a.IsEnterprisePartner when 1 then a.UserId else d.UpEnterpriseUserId end) as UpEnterpriseUserId,
(case a.IsEnterprisePartner when 1 then d.UpEnterpriseUserId else d.UpTwoEnterpriseUserId end) as UpTwoEnterpriseUserId,(case a.IsEnterprisePartner when 1 then d.UpTwoEnterpriseUserId else d.UpThreeEnterpriseUserId end) as UpThreeEnterpriseUserId
FROM aspnet_Distributors a INNER JOIN D ON a.ReferralUserId=D.UserID
)
select D.* from D

– IsEnterprisePartner(是否是合伙人), UpEnterpriseUserId(上级合伙人Id),UpTwoEnterpriseUserId(上上级合伙人Id),UpThreeEnterpriseUserId上上上级合伙人Id)
–自己标识是1就是自己,不是就是上级,再不是就是上级的上级

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值