1.|+----------------+-------------------+|||2 7 9|||+--+--+|+--+--+|||||3 4 8 10 12||+-+-+||||5 6 11
注意:我无法发布图像,所以尝试将上面的数字视为以1为根节点的树结构
我如何使用分层查询来获得两个节点之间的路径
例如:11和4 之间的路径
即输出应为
11-10
10-9
9-1
1-2
2-4
您可以从叶子开始向上爬:
select p_n || ' - ' || n
from t
where p_n is not null
start with n = 11
connect by prior p_n = n
order by level desc
这是一个sqlfiddle演示
编辑:好吧,这让事情变得有点复杂。。。
你可以从两个节点向上爬,但之后你必须删除重复的路径(例如,在6到3之间,不需要通过根1)
试试这样的东西:
select the_path
from
(select case when connect_by_root(n) = 11 then p_n || ' - ' || n else n || ' - ' || p_n end the_path,
count(*) over (partition by n, p_n) cnt
from t
where p_n is not null
start with n in (11, 4)
connect by prior p_n = n)
where cnt = 1;
这是另一个sqlfiddle演示