【问题标题】:Query with cycle (Oracle 10 XE and 11 XE)循环查询(Oracle 10 XE 和 11 XE)
【发布时间】:2013-04-24 19:19:41
【问题描述】:

有路线图(连接城市列表):

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

返回:错误 ORA-01436 CONNECT BY 在用户数据中循环

任何建议,如何通过分层查询获得预期结果?

【问题讨论】:

  • 如果我们插入下面的订单查询给出预期的结果。插入 aaa 值(1,0);插入 aaa 值 (2,1);插入 aaa 值 (3,2);插入 aaa 值 (4,3);
  • 我认为您的意思是插入 aaa 值 (3,2);不插入 aaa 值 (2,3);
  • 没有。所有的插入查询,其中的ov值顺序都是对的。

标签: sql oracle hierarchical hierarchical-query


【解决方案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

【讨论】:

  • 谢谢您的建议。但在我的问题中,我无法按行设置值的顺序。我已经用新的输入数据重写了问题来描述。
  • @potapuff - 答案已更新。关键是在将无向图提供给 Oracle 分层查询之前将其转换为有向图。
猜你喜欢
  • 2014-10-20
  • 1970-01-01
  • 2019-01-24
  • 2017-09-01
  • 2017-12-08
  • 2016-04-26
  • 2019-09-14
  • 2010-10-20
  • 2016-12-13
相关资源
最近更新 更多