SqlServer中递归查询父节点及其所属子节点

需求场景

递归查询父节点及其所属子节点

SQL脚本实现-根据子节点查询所有的父节点

 -- 查找所有父节点
with tab as
(
 select pc.id,pc.ParentId,pcd.Name,1 as [level] from ProductCategories pc join ProductCategoryDescriptions pcd on pcd.ProductCategoryId=pc.Id and pcd.LanguageId='en' --where id=1--子节点
 union all
 select a.id--当前节点Id
 ,b.ParentId,--父节点Id
 c.Name --父节点名称,关联可以修改为【a.Id=c.ProductCategoryId】就表示当前节点名称
 ,a.[level]+1--层级
 from
  tab a,--子节点数据集
  ProductCategories b , --父节点数据集
  ProductCategoryDescriptions c  --父节点数据集
 where a.ParentId=b.Id and b.Id=c.ProductCategoryId and c.LanguageId='en' --子节点数据集.parendID=父节点数据集.ID
)
select * from tab where id=149;
 

查询结果

在这里插入图片描述
这里的Level是倒序的,也就是当前数据为第一层,level的大小由father、ancestors一次递增,max(level)表示祖先

SQL脚本实现-根据父节点查询所有的子节点

 -- 根据父节点查找所有子节点
with a as (
select id, parentid from ProductCategories where id=124
union all
select x.id, x.parentid from ProductCategories x,a where x.parentid=a.id
)
select * from a
 

查询结果

在这里插入图片描述
这里的Level是倒序的,也就是当前数据为第一层,level的大小由father、ancestors一次递增,max(level)表示祖先

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值