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