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
ORDER BY pid
从末梢往树ROOT递归(取全部“父爷”集):
SELECT * FROM TBL_TEST
start WITH id=5
connect BY prior pid = id
ORDER BY id