如何在MySQL递归查询中求和

时间:2018-11-10 19:01:40

标签: mysql

我的问题陈述是:我需要找到可以从Origin'A'游览的地方及其各自的费用。

这是我的表Train(来源,目的地,最低费用)

 +--------+-------------+------+
 | Origin | Destination | cost |
 +--------+-------------+------+
 | A      | B           |    1 |
 | A      | C           |    4 |
 | B      | C           |    2 |
 | A      | D           |    4 | 
 +--------+-------------+------+

我尝试查询:

with recursive Final(Origin, Destination, LeastCost) As(
-> (Select * from Train)
-> UNION
-> (Select T.Origin, F.Destination, F.LeastCost
-> from Train T, Final F
-> where T.Destination = F.Origin))
-> select * from Final ;

这给了我

+--------+-------------+-----------+
| Origin | Destination | LeastCost |
+--------+-------------+-----------+
| A      | B           |         1 |
| A      | C           |         4 |
| B      | C           |         2 |
| A      | D           |         4 |
| A      | C           |         2 |
+--------+-------------+-----------+

我正在寻找的结果是

Origin | Destination | Price |
 A            C          3

由于A-> B = 1,B-> C = 2,所以最后一行中的A-> C = 1 + 2 = 3。

我该如何实现?我尝试在递归查询中使用SUM(LeastCost),但MySQl不允许在那里进行聚合。

1 个答案:

答案 0 :(得分:0)

在递归查询中将T和F别名中的两个成本加在一起。 然后在最终查询中添加其他逻辑以对结果进行分组:

with recursive Final(Origin, Destination, LeastCost) As(
    (Select * from Train)
    UNION
    (Select T.Origin, F.Destination, T.cost + F.LeastCost
     from Train T, Final F
     where T.Destination = F.Origin)
)
select   Origin, Destination, min(LeastCost)
from     Final
group by Origin, Destination

通过递归机制T.cost + F.LeastCost,当您从一个节点穿过树到另一个节点时,将使成本相加。