[Oracle整理]树形查询(start with connect by)

说明:本内容是工作用到的知识点整理,来自工作中和网络。
代码于Oracle9上测试。

 

树形查询(start with connect by)

作用:

Start with...Connect By子句

递归查询一般用于一个表维护树形结构的应用

语法:

SELECT …

CONNECT BY  PRIOR列名1=列名2 (列名1=PRIOR列名2 )

[START WITH]

Where condition

注意:

PRIOR运算符在一侧表示父节点,在另一侧表示子节点,从而确定查找树结构是的顺序是自顶向下还是自底向上

CONNECT BY PRIOR ID=PRAENTID :上一条记录的ID是本条记录的PRAENTID,即本记录的父亲是上一条记录

例子:

要实现的效果

clip_image002

step1创建测试表

-- 1
create table xx_test2
(
folder_id number,
folder_name varchar2(255),
parent_id number
)

setp2添加数据

-- 2
insert into xx_test2 values(1,'C',10000);
insert into xx_test2 values(2,'Windows',1);
insert into xx_test2 values(3,'System32',2);
insert into xx_test2 values(4,'Config',3);

step3实现

-- 3
SELECT folder_id, folder_name, parent_id, LEVEL
  FROM xx_test2
CONNECT BY PRIOR folder_id = parent_id
 START WITH folder_id = (SELECT folder_id
                           FROM (SELECT folder_id, parent_id
                                   FROM xx_test2
                                 CONNECT BY folder_id = PRIOR parent_id
                                  START WITH folder_id = 1)
                          WHERE parent_id = 10000)
 ORDER BY LEVEL

clip_image004

注意:

Level是关键字,可以直接使用。表示树形的层级,即深度。

posted @ 2012-01-29 11:17  yellowwood  阅读(296)  评论(0编辑  收藏  举报
Never Give UP