sql递归

1.正常递归

with
district as
(
  --  获得第一个结果集
  select * from z_tree where node_name= N'辽宁省'
  union all
  --  下面的select语句首先会根据从上一个查询结果集中获得的id值来查询parent_id    
  --  字段的值,然后district就会变当前的查询结果集,并继续执行下面的select 语句
  --  如果结果集不为null,则与最终的查询结果合并,同时用合并的结果更新最终的查
  --  询结果;否则停止执行。最后district的结果集就是最终结果集。
  select a.* from z_tree a join district b
        on a.parent_id = b.id
)
select * from district

 

2.反向递归

with  t as(
     select * from company where id ='B3'
     union  all
     select c.* from t ,company c  where t.pid=c.id
 )   
 select * from t

posted @ 2020-01-14 16:01  番茄蛋汤  阅读(467)  评论(0编辑  收藏  举报