oracle A点出发到各地的路径及其距离

求所有的可能路径及距离,样例数据如下:

with bus as
(
select 1 id, 'A' dstart, 'B' dend, '120' distance from dual union all
select 2 id, 'B' dstart, 'C' dend, '200' distance from dual union all
select 3 id, 'C' dstart, 'E' dend, '180' distance from dual union all
select 4 id, 'A' dstart, 'D' dend, '150' distance from dual union all
select 5 id, 'D' dstart, 'M' dend, '300' distance from dual union all
select 6 id, 'F' dstart, 'M' dend, '260' distance from dual
)
select * From bus;

实现效果:

SUM_DISTANCE	PATH
120		A->B
320		A->B->C
500		A->B->C->E
150		A->D
450		A->D->M
200		B->C
380		B->C->E
180		C->E
300		D->M
260		F->M

原始SQL代码:

with bus as
(
select 1 id, 'A' dstart, 'B' dend, '120' distance from dual union all
select 2 id, 'B' dstart, 'C' dend, '200' distance from dual union all
select 3 id, 'C' dstart, 'E' dend, '180' distance from dual union all
select 4 id, 'A' dstart, 'D' dend, '150' distance from dual union all
select 5 id, 'D' dstart, 'M' dend, '300' distance from dual union all
select 6 id, 'F' dstart, 'M' dend, '260' distance from dual 
)
select level, a.dstart, a.dend, 
       sys_connect_by_path(distance,'+')  sum_distance,
       (select sum(b.distance) from bus b start with b.id=a.id connect by prior dstart =  dend
       ),
       CONNECT_BY_root(a.dstart)|| sys_connect_by_path(a.dend,'->')  path,
       CONNECT_BY_ISLEAF leaf      
from bus a
connect by prior dend =  dstart;

一看这个SQL语句里有一个标量子查询,数据量少的时候看不出来问题,多的时候就会出现性能问题,因此利用dbms_aw.eval_number函数处理了树形函数的返回值, 优化后的SQL代码 :

with bus as
(
select 1 id, 'A' dstart, 'B' dend, '120' distance from dual union all
select 2 id, 'B' dstart, 'C' dend, '200' distance from dual union all
select 3 id, 'C' dstart, 'E' dend, '180' distance from dual union all
select 4 id, 'A' dstart, 'D' dend, '150' distance from dual union all
select 5 id, 'D' dstart, 'M' dend, '300' distance from dual union all
select 6 id, 'F' dstart, 'M' dend, '260' distance from dual 
)
select level, a.dstart, a.dend, ltrim(sys_connect_by_path(distance,'+'),'+') distance_expression,
       dbms_aw.eval_number(ltrim(sys_connect_by_path(distance,'+'),'+'))  sum_distance,
       CONNECT_BY_root(a.dstart)|| sys_connect_by_path(a.dend,'->')  path,
       CONNECT_BY_ISLEAF leaf      
from bus a
connect by prior dend =  dstart;

参考:http://blog.csdn.net/jgmydsai/article/details/38985577

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值