带路线的表格:
route_id | points
1 | [A,B]
2 | [L,G,C,F,E]
表格中包含路线段的费用:
route_id | point A | pointB | cost
1 | A | B | 10
2 | L | G | 10
2 | G | C | 20
2 | C | F | 15
2 | F | E | 13
有必要计算route_id = 2中点'G'和'E'之间的成本
答案 0 :(得分:0)
您可以使用" Recursive With Clause"来实现您想要的结果。
表:
create table test(
route_id int,
pointA char,
pointB char,
cost int
);
值:
insert into test values(1 ,'A','B',10),
(2 ,'L','G',10),
(2 ,'G','C',20),
(2 ,'C','F',15),
(2 ,'F','E',13)
递归查询:
WITH RECURSIVE routecost AS (
SELECT pointA, pointB ,cost /* non recursive part */
FROM test
WHERE pointA = 'G'
and route_id = 2
UNION ALL
SELECT b.pointA, a.pointB, a.cost + b.cost /* recursive part */
FROM test a
JOIN routecost b ON(a.pointA = b.pointB)
where a.route_id = 2
)
SELECT * FROM routecost
where pointB = 'E'
说明: