背景条件:使用的数据库为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语句,下面是我的个人微信公众号:编码与生活,欢迎关注