oracle中的树形查询

基本语法

select...from tabename start with cond1 connect by  prior cond2 where cond2

注:cond1是根节点的限定语句

cond2是连接条件,其中prior表示上一条记录,指该记录的父亲是上一条记录

cond3是过滤条件

构造环境:不说你懂的

create table Family(
id integer,
parentid integer,
name varchar2(50)
)

insert into family values(0,0,'a')
insert into family values(1,0,'b')
insert into family values(2,1,'c')
insert into family values(3,1,'d')
insert into family values(4,1,'e')
insert into family values(5,1,'f')

例一:通过根节点遍历子节点

--查询父亲等于1的所有子的信息
select * from family start with parentid=1 connect by prior id=parentid

例二:通过子节点向根节点追溯

select * from family start with id=5 connect by prior parentid=id

注:如果报ORA-01436:用户数据库中的coonect by循环,则将第一条数据中的parentid改为null,否则loop循环找parentid就找不到了!

扩展:通过level 关键字查询所在层次

select t.*,level from family t start with parentid=1 connect by prior id=parentid --表必须用别名

转载于:https://www.cnblogs.com/muzizhu/archive/2011/08/16/2140719.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值