简体   繁体   English

如何在MySQL递归查询中求和

[英]How to sum in MySQL recursive query

My problem statement is: I need to find places I can visit from Origin 'A' and their respective costs. 我的问题陈述是:我需要找到可以从出发地“ A”前往的地点及其各自的费用。

This is my table Train(Origin, Destination, LeastCost) 这是我的桌子火车(始发地,目的地,最低费用)

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

I have tried a query: 我试过查询:

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 ;

This gives me: 这给了我:

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

The result I am looking for is 我正在寻找的结果是

Origin | Destination | Price |
 A            C          3

As A-->B = 1, B-->C=2 , So A-->C=1+2=3 in the last row. 由于A-> B = 1,B-> C = 2,所以最后一行中的A-> C = 1 + 2 = 3。

How do I achieve this? 我该如何实现? I tried using SUM(LeastCost) inside the recursive query but MySQl doesn't allow aggregations in there. 我尝试在递归查询中使用SUM(LeastCost),但MySQl不允许在那里进行聚合。

Add the two costs from the T and F aliases together in the recursive query. 在递归查询中将T和F别名中的两个成本加在一起。 And then put additional logic in the final query to group the results: 然后在最终查询中添加其他逻辑以对结果进行分组:

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

Through the recursive mechanism T.cost + F.LeastCost will make the cost sum up as you travel from one node through the tree to another. 通过递归机制, T.cost + F.LeastCost将使您在从一个节点穿过树到另一个节点的过程中T.cost + F.LeastCost成本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM