2013-04-24 54 views
0

有路線圖(連接城市清單):查詢與週期(甲骨文10 XE和11 XE)

drop table aaa; 
create table aaa(a varchar2(10), b varchar2(10)); 
insert into aaa values ('Rome','Berlin'); 
insert into aaa values ('London','Rome'); 
insert into aaa values ('London','New-York'); 
insert into aaa values ('New-York','Dallas'); 

我需要的路徑:柏林=>羅馬=>新紐約=>達拉斯

變型1:

select sys_connect_by_path(DECODE(a, PRIOR a, b, a),'=>') PATH1 
from aaa 
start with a = 'Berlin' or b = 'Berlin' 
connect by nocycle Prior a = b or prior b = a 

回程:=>羅馬=>倫敦

變體2:

select sys_connect_by_path(DECODE(a, PRIOR a, b, a),'=>') PATH1 
from aaa 
start with a = 'Berlin' or b = 'Berlin' 
connect by Prior a = b or prior b = a 

返回:ERROR ORA-01436 CONNECT BY循環用戶數據

任何建議,如何獲得預期的結果與分層查詢

+0

如果我們在下面的順序查詢給出預期的結果插入。插入到aaa值(1,0); 插入aaa值(2,1);插入到aaa值(3,2);插入到aaa值(4,3)中的 ; – VKPRO 2013-04-24 19:30:51

+0

我想你的意思是插入到aaa值(3,2);不插入到aaa值(2,3); – Randy 2013-04-24 21:03:32

+0

不是。所有插入查詢,訂單ov值都是正確的。 – potapuff 2013-04-25 04:38:06

回答

1
select 
    sys_connect_by_path(b,'=>') PATH1 
from 
(
    select 
    least(a, b) a, 
    greatest(a, b) b 
    from aaa 
) 
start with a = 0 
connect by prior b = a 

UPD:

select 
    sys_connect_by_path(b, '=>') PATH1 
from 
    (
    select a, b from aaa 
    union all 
    select b, a from aaa 
    union all 
    select null, 'Berlin' from dual 
) 
start with a is null 
connect by nocycle prior b = a 
+0

謝謝你的建議。但在我的問題中,我無法在行中設置值的順序。我用新的輸入數據重寫問題來描述。 – potapuff 2013-04-25 04:52:01

+1

@potapuff - 答案已更新。重點是將您的無向圖轉換爲定向圖,然後再將它提供給Oracle分層查詢。 – 2013-04-25 05:45:32