SQL--数据库树形结构查询树节点及其所有子节点(递归查询),使用with as子查询

背景条件:使用的数据库为SQL SERVER 2008, 数据库通过pid字段来标识该条记录的父节点记录,我需要查询出该节点及其递归下面的所有子节点,经查询使用with as 可以达到递归查询的功能,WITH AS短语,也叫做子查询部分(subquery factoring),给子查询取个别名,在其他用到的地方就可以通过别名来引用
catalog 表结构如下:id, pid
在这里插入图片描述
仅仅是查询出id字段,SQL为:

with f(id) as 
        (
            select id from catalog where id = 34 
            union all
            select a.id from catalog as a inner join f as b on a.pid = b.id
        )
        select * from f

查询结果如下
在这里插入图片描述
如果是查询出表的所有字段,SQL为:

with f as 
        (
            select * from catalog where id = 34 
            union all
            select a.* from catalog as a inner join f as b on a.pid = b.id
        )
        select * from f

以上就是用with as进行递归查询的SQL语句,下面是我的个人微信公众号:编码与生活,欢迎关注

欢迎关注微信公众号:编码与生活,一起成长,小白的进阶之路

在这里插入图片描述

发布了2 篇原创文章 · 获赞 0 · 访问量 20

猜你喜欢

转载自blog.csdn.net/rbw204/article/details/105380856