1. 我們建一個表 test2 舉例說明 oracle 遞歸查詢的兩種方法。
數據結構如下:
2. 我們的目標是查找A1下面所有的子節點和所處層級。
A.通用做法:寫一個遞歸SQL 如下
select t.*, level
from test2 t
start with t.father = 'A1'
connect by t.father = prior t.child
order by level
結果:
B.替代做法:
with all_test(father,
child,
levelno) as
(select t.father, t.child, 1
from test2 t
where t.father = 'A1'
union all
select t2.father, t2.child, at.levelno + 1
from test2 t2, all_test at
where at.child = t2.father)
select * from all_test
結果:
3. 從以上兩種結果來看,結果一樣。經測試數據量很大的情況下,B,替代做法效率較高。