oracle--SQL之树(start with... connect by prior...)

connect by 是结构化查询中用到的,其基本语法是:

select ... from tablename start with 条件1
connect by 条件2
where 条件3;
--例:
select * from table
start with org_id = 'HBHqfWGWPy'
connect by prior org_id = parent_id; 

简单说来是将一个树状结构存储在一张表里,比如一个表中存在两个字段:
org_id,parent_id那么通过表示每一条记录的parent是谁,就可以形成一个树状结构。
用上述语法的查询可以取得这棵树的所有记录。
其中:
条件1 是根结点的限定语句,当然可以放宽限定条件,以取得多个根结点,实际就是多棵树。
条件2 是连接条件,其中用PRIOR表示上一条记录,比如 CONNECT BY PRIOR org_id = parent_id就是说上一条记录的org_id 是本条记录的parent_id,即本记录的父亲是上一条记录。
条件3 是过滤条件,用于对返回的所有记录进行过滤。


例如:
没有加中start with ... connect by prior ...的查询结果:

select t.dim_id, t.pid, level
from pmcode.pmcode_fj_tree_rl t
where t.dim_id in (select b.dim_id
                   from pmcode.PMCODE_KPI_DIM_OD b
                   where b.kpi_id = 'KC0011')
结果:
DIM_ID PID LEVEL
---------------------
1024 5003 0
1070 0 0
5003 1070 0
5006 0 0
------------------------------------------------------------------------------------
增加start with ... connect by prior ...以后的结果:

select t.dim_id, t.pid, level
from pmcode.pmcode_fj_tree_rl t
where t.dim_id in (select b.dim_id
                   from pmcode.PMCODE_KPI_DIM_OD b
                   where b.kpi_id = 'KC0011')
start with t.dim_id = '1070' ----表示从dim_id = '1070'开始(也就是说1070为根节点)

connect by prior t.dim_id = t.pid; ----表示上条记录的dim_id等于本条记录的pid
结果:
DIM_ID PID LEVEL
---------------------
1070 0 1
5003 1070 2
1024 5003 3

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值