我有一个包含此信息的数据库:
trip1 => stop1
trip1 => stop15
trip1 => stop20
trip2 => stop8
trip2 => stop11
trip2 => stop17
trip3 => stop15
trip3 => stop11
trip3 => stop25
如果用户想要从stop1转到stop17,我会打印此信息:
stop1 (trip1) => stop15 (trip3) => stop11 (trip2) => stop17
是否可以通过sql请求获取对应的stop15和stop11?我是通过使用pl sql来做的。
答案 0 :(得分:1)
你需要这里的最短路径算法,如@Eng。 Samer T写道。
一个天真的查询为这个样本数据生成所有可能的路径,从stop1到stop17提供了8个可能的路径,而你指向的路径是最短路径。
看看这个例子:http://sqlfiddle.com/#!4/7742c/13
随着更多的数据,这个天真的查询可能永远不会完成,因为一些可能的路径可能是无穷无尽的。
SELECT "Path"
FROM (
select trip,
pidstop,
CONNECT_BY_ROOT trip as root_pid,
CONNECT_BY_ROOT pidstop As root_pidstop,
SYS_CONNECT_BY_PATH(pidstop||' ('||trip||') ',
'/') As "Path"
from table1
start with pidstop = 'stop1'
connect by nocycle
prior pidstop = pidstop
and prior trip <> trip
or
prior trip = trip
and prior pidstop <> pidstop
)
WHERE root_pidstop = 'stop1'
AND pidstop = 'stop17'
/stop1 (trip1) /stop15 (trip1) /stop15 (trip3) /stop11 (trip3) /stop11 (trip2) /stop8 (trip2) /stop17 (trip2)
/stop1 (trip1) /stop15 (trip1) /stop15 (trip3) /stop11 (trip3) /stop11 (trip2) /stop17 (trip2)
/stop1 (trip1) /stop15 (trip1) /stop15 (trip3) /stop25 (trip3) /stop11 (trip3) /stop11 (trip2) /stop8 (trip2) /stop17 (trip2)
/stop1 (trip1) /stop15 (trip1) /stop15 (trip3) /stop25 (trip3) /stop11 (trip3) /stop11 (trip2) /stop17 (trip2)
/stop1 (trip1) /stop20 (trip1) /stop15 (trip1) /stop15 (trip3) /stop11 (trip3) /stop11 (trip2) /stop8 (trip2) /stop17 (trip2)
/stop1 (trip1) /stop20 (trip1) /stop15 (trip1) /stop15 (trip3) /stop11 (trip3) /stop11 (trip2) /stop17 (trip2)
/stop1 (trip1) /stop20 (trip1) /stop15 (trip1) /stop15 (trip3) /stop25 (trip3) /stop11 (trip3) /stop11 (trip2) /stop8 (trip2) /stop17 (trip2)
/stop1 (trip1) /stop20 (trip1) /stop15 (trip1) /stop15 (trip3) /stop25 (trip3) /stop11 (trip3) /stop11 (trip2) /stop17 (trip2)