Oracle start with...connect by prior 實現遞迴查詢,oracle遞迴查詢
基本文法:
<span style="font-size:18px;"><em>select ... from <TableName>where <Conditional-1>start with <Conditional-2>connect by <Conditional-3>;<Conditional-1>:過濾條件,用於對返回的所有記錄進行過濾。<Conditional-2>:查詢結果重起始根結點的限定條件。<Conditional-3>:串連條件</em></span>
資料表結構如下:
create table table_test(priorId number,id number,name varchar(5),description varchar(10));
測試資料:
insert into table_test(priorId,id,name,description) values(0,1,'f','f父類');insert into table_test(priorId,id,name,description) values(1,2,'f1','f子類1');insert into table_test(priorId,id,name,description) values(1,3,'f2','f子類2');insert into table_test(priorId,id,name,description) values(0,4,'F','F父類');insert into table_test(priorId,id,name,description) values(4,5,'F1','F子類1');insert into table_test(priorId,id,name,description) values(4,6,'F2','F子類2');
擷取完整樹:
select * from table_test start with priorId = 0 connect by prior id = priorId;
擷取特定子樹:
select * from table_test start with id = 1 connect by prior id = priorId;select * from table_test start with id = 4 connect by prior id = priorId;
如果connect by prior中的prior被省略,則查詢將不進行深層遞迴:
select * from table_test start with priorId = 0 connect by id = priorId;select * from table_test start with id = 1 connect by id = priorId;