Oracle数据库遍历树形结构表

1、从根结点开始找子节点

/*
create table test (id  int ,pid int ,name varchar(10));
insert into test values ( 1, 0 ,'n1' );
insert into test values(  2, 1 ,'n12');
insert into test values(  3, 1 ,'n13');
insert into test values(  4, 2 ,'n21');
insert into test values(  5, 2 ,'n22');
insert into test values(  6, 3 ,'n31');
insert into test values(  7, 3 ,'n32');
insert into test values(  8, 4 ,'n211');
insert into test values(  9, 4 ,'n212');
*/
/*
从根结点开始找子节点(可以指定节点层级)
*/

select id,pid,name ,level from test
--where level =3
start with id =2
connect by prior id =  pid;

 

2、从叶结点开始找根节点

/*
create table test (id  int ,pid int ,name varchar(10));
insert into test values ( 1, 0 ,'n1' );
insert into test values(  2, 1 ,'n12');
insert into test values(  3, 1 ,'n13');
insert into test values(  4, 2 ,'n21');
insert into test values(  5, 2 ,'n22');
insert into test values(  6, 3 ,'n31');
insert into test values(  7, 3 ,'n32');
insert into test values(  8, 4 ,'n211');
insert into test values(  9, 4 ,'n212');
*/
/*
从叶结点开始找根节点
prior 关键字 与谁放在一起,就是找谁
根节点的父节点不能是他本身,那会造成死循环
*/

select *  from test /*where conditions*/
start with id=7
connect by id = prior pid;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值