【问题标题】:MySQL get sum of fields which rows refer to the two records in another table in between selected rowsMySQL获取字段总和,哪些行在选定行之间引用另一个表中的两条记录
【发布时间】:2013-05-05 01:47:26
【问题描述】:

抱歉标题含糊不清,但我不太确定如何命名此过程。所以问题是我有两张桌子。第一个代表火车站及其顺序:

station_id | station_name 
1          |  station1 
2          |  station2 
3          |  station3 
4          |  station4 
5          |  station5 
6          |  station6 

第二个表代表从一个站到另一个站乘坐火车的价格(列station1_idstation2_id是上表列station_id的外键):

price_id | station1_id | station2_id | price 
1        |  1          |  2          |  0.4  
2        |  2          |  3          |  0.35 
3        |  3          |  4          |  0.32 
4        |  4          |  5          |  0.20 
5        |  5          |  6          |  0.25 

我想做的是为想要从 A 站乘火车到 B 站的人计算车票的价格。例如,如果 A 站是“station2”,B 站是“station5”,那么我想要我的查询返回“0.87”。

也许有人可以就如何解决 A 站在 B 站之后的情况提出建议,即查询需要计算从下到上的票价。

提前谢谢你。

【问题讨论】:

    标签: mysql reference sum field outer-join


    【解决方案1】:
    SELECT SUM(price)
      FROM prices
      WHERE station1_id >= station1 AND station1_id < station2;
    

    station2_id 列是多余的。

    【讨论】:

      猜你喜欢
      • 2015-08-28
      • 1970-01-01
      • 2011-10-12
      • 1970-01-01
      • 2023-02-04
      • 1970-01-01
      • 2021-02-04
      • 2020-07-21
      • 1970-01-01
      相关资源
      最近更新 更多