树-Oracle用Start with...Connect By子句递归查询

转 。。。。。。。。。。。。。。。。。。。。。。。。。
Start with...Connect By子句递归查询一般用于一个表维护树形结构的应用。
prompt PL/SQL Developer import file
prompt Created on 2010年12月23日 by qcy
set feedback off
set define off
prompt Dropping TBL_TEST...
drop table TBL_TEST cascade constraints;
prompt Creating TBL_TEST...
create table TBL_TEST
(
  ID   NUMBER not null,
  NAME VARCHAR2(100),
  PID  NUMBER default 0
)
tablespace STD
  pctfree 10
  initrans 1
  maxtrans 255
  storage
  (
    initial 64K
    minextents 1
    maxextents unlimited
  );
alter table TBL_TEST
  add constraint PK_TBK_TEST primary key (ID)
  using index 
  tablespace STD
  pctfree 10
  initrans 2
  maxtrans 255
  storage
  (
    initial 64K
    minextents 1
    maxextents unlimited
  );

prompt Disabling triggers for TBL_TEST...
alter table TBL_TEST disable all triggers;
prompt Loading TBL_TEST...
insert into TBL_TEST (ID, NAME, PID)
values (1, '10', 0);
insert into TBL_TEST (ID, NAME, PID)
values (2, '11', 1);
insert into TBL_TEST (ID, NAME, PID)
values (3, '20', 0);
insert into TBL_TEST (ID, NAME, PID)
values (4, '12', 1);
insert into TBL_TEST (ID, NAME, PID)
values (5, '121', 2);
commit;
prompt 5 records loaded
prompt Enabling triggers for TBL_TEST...
alter table TBL_TEST enable all triggers;
set feedback on
set define on
prompt Done.
  
从Root往树末梢递归
select * from TBL_TEST
 start with id=1
 connect by prior id = pid
 
从末梢往树ROOT递归
select * from TBL_TEST
 start with id=5
 connect by prior pid = id
=====

对于oracle进行简单树查询(递归查询)

 

DEPTIDPAREDEPTIDNAME
NUMBERNUMBERCHAR (40 Byte)
部门id父部门id(所属部门id)部门名称

 

通过子节点向根节点追朔.

  SQL
 select * from persons.dept start with deptid=76 connect by prior paredeptid=deptid

通过根节点遍历子节点.

Sql代码
select * from persons.dept start with paredeptid=0 connect by prior deptid=paredeptid 
  

可通过level 关键字查询所在层次.

Sql代码
select a.*,level from persons.dept a start with paredeptid=0 connect by prior deptid=paredeptid 

 

再次复习一下:start with ...connect by 的用法, start with 后面所跟的就是就是递归的种子

递归的种子也就是递归开始的地方 connect by 后面的"prior" 如果缺省:则只能查询到符合条件的起始行,并不进行递归查询;

connect by prior 后面所放的字段是有关系的,它指明了查询的方向

练习: 通过子节点获得顶节点

Sql代码 复制代码
  1. select FIRST_VALUE(deptid) OVER (ORDER BY LEVEL DESC ROWS UNBOUNDED PRECEDING) AS firstdeptid from persons.dept start with deptid=76 connect by prior paredeptid=deptid  

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值