Oracle 递归查询

Oracle递归查询的格式:

正向递归(从上到下):

select * from table
start with id = x
connect by prior id = parentid;
start with 后面的条件指定遍历的根节点,connect by prior 后面的条件表明查询过程中的叶子节点再次作为根节点进行递归查询。

反向递归(从下到上):

select * from table
start with id = x
connect by prior  parentid = id;
注意parentid和id的位置互换了。

举例:

表tree:


id是记录自己的主键,parentid存放了上级的id,总部是最高级,parentid=-1,中心上级是总部,parentid=1

一.上级向下递归

1.查询中心,并且包含他下面的服务商的所有记录。

select * from tree
start with id = 2
connect by prior id = parentid;

结果:

2 1 中心
3 2 服务商
4 2 服务商

这条Sql等价于:

select * from tree
start with parentid = 1
connect by prior id = parentid;

2.查询总部,并且包含他下面的中心,服务商的所有记录。

select * from tree
start with id = 1
connect by prior id = parentid;

1 -1 总部
2 1 中心
3 2 服务商1
4 2 服务商2

等价于:

select * from tree
start with parentid = -1
connect by prior id = parentid;

二.从下往上递归(反向递归)

1.中心查自己和总部:

select * from tree
start with id = 2
connect by prior parentid = id;
2 1 中心
1 -1 总部

2.服务商1查自己和中心,总部:

select * from tree
start with id = 3
connect by prior parentid = id;
3 2 服务商1
2 1 中心
1 -1 总部

三.省略start with:

省略start with意味着不指定具体根节点,把每个节点当作根节点遍历一次。

select * from tree
connect by prior id = parentid;

1 -1 总部
2 1 中心
4 2 服务商2
3 2 服务商1
2 1 中心
4 2 服务商2


等价于:

select * from tree
start with id in(1,2,3,4)
connect by prior  id = parentid;

四.where条件过滤

where条件要加在 from 后面,start with前:

select * from tree where id <>3
start with parentid = -1
connect by prior id = parentid;

1 -1 总部
2 1 中心
4 2 服务商2

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值