|
|
用SQL暴力算了一小时:
create table p2 as
with d as (
select 1 id,1 d from dual union all
select 2,23 from dual union all
select 3,34 from dual union all
select 4,125 from dual union all
select 5,145 from dual )
,p as (
select cast(sys_connect_by_path(from_id||':'||to_id||':'||len,',') as varchar2(1000)) as path,to_id
from trip
where to_id in (select d from d)
start with from_id=12345
connect by from_id=prior to_id
)
,p2 (path,to_id,cnt) as (
select cast(path as varchar2(2000)),to_id,d.id from p,d where p.to_id=d.d and d.id=1
union all
select cast(p2.path||p.path as varchar2(2000)),p.to_id,p2.cnt+1
from p2,p,d
where p2.cnt+1=d.id and p.to_id=d.d
)
select * from p2 where cnt=5;
select * from (
select *
from p2
,lateral(
select sum(distance) as distance
from ( select distinct from_id,to_id,distance
from (select regexp_substr(node,'[^:]+',1,1) from_id,regexp_substr(node,'[^:]+',1,2) to_id,regexp_substr(node,'[^:]+',1,3) distance
from ( select regexp_substr(p2.path,'[^,]+',1,level) as node
from dual
connect by level<=regexp_count(p2.path,',')
)
)
)
)
order by distance
)
where rownum=1;
PATH
-----------------------------------------------------------------------------------------------------------------------------
TO_ID CNT DISTANCE
---------- ---------- ----------
,12345:125:30,125:1:0,12345:1234:49,1234:234:0,234:23:1,12345:1234:49,1234:134:0,134:34:0,12345:125:30,12345:145:50
145 5 130
Elapsed: 00:00:54.68
|
|