日期:2014-05-16  浏览次数:20597 次

Oracle Start with...Connect By 使用方法
Start with...Connect By子句递归查询一般用于一个表维护树形结构的应用。

创建示例表:

CREATE TABLE TBL_TEST
(
? ID??? NUMBER,
? NAME? VARCHAR2(100 BYTE),
? PID?? NUMBER????????????????????????????????? DEFAULT 0
);

?

插入测试数据:

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');

?

从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
1 楼 bo_hai 2012-03-07  
SELECT *
FROM CATEGORY C
CONNECT BY PRIOR C.ID = C.CATEGORY_PARENT_ID
 START WITH C.ID = 123


理解为:当前行记录id是下一行记录的父ID,用于从顶层往低层查询。
SELECT * FROM CATEGORY c 
CONNECT BY PRIOR c.category_parent_id = c.id
START WITH c.id = 1069


理解为:当前行的父ID是下一条记录的ID,用于从低层往顶层查询。