2013-07-23 23 views
3
 
         1 
         | 
     +----------------+-------------------+ 
     |    |     | 
     2    7     9 
     |    |     | 
    +--+--+    |    +--+--+ 
    |  |    |    |  | 
    3  4    8    10  12 
     |        | 
     +-+-+       | 
     | |       | 
     5 6       11 

注意:我無法發佈圖像,因此請嘗試將上面的數字視爲以1作爲根節點的樹結構。Oracle SQL分層查詢知道兩個元素之間的路徑

如何使用分層查詢來獲取兩個節點

用於例如之間的路徑:11和4

之間的路徑,即輸出應該

11-10
10-9
9-1
1-2
2-4

回答

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 

Here is a sqlfiddle demo


編輯: OK,這使事情變得有點複雜......

你可以從兩個節點上爬,但是必須刪除重複的路徑(例如在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; 

Here is another sqlfiddle demo

+0

感謝您的答覆......我沒有張貼我的問題properly..have現在更新它! –