Oracle 递归查询

来源:互联网 发布:风险管理矩阵图 编辑:程序博客网 时间:2024/05/22 19:00

Oracle递归查询的格式:

正向递归(从上到下):

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

反向递归(从下到上):

select * from tablestart with id = xconnect by prior  parentid = id;
注意parentid和id的位置互换了。

举例:

表tree:


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

一.上级向下递归

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

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

结果:

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

这条Sql等价于:

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

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

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

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

等价于:

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

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

1.中心查自己和总部:

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

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

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

三.省略start with:

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

select * from treeconnect by prior id = parentid;

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


等价于:

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

四.where条件过滤

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

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

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

0 0
原创粉丝点击