您的位置:首页 > 数据库 > Oracle

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

2013-05-21 16:31 513 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: