Mysql select每个值选择3次

时间:2017-03-03 01:35:39

标签: mysql

我运行此查询:

SELECT routes.route_number, routes.frequency 
FROM routes, 
  (SELECT proportion FROM operation_proportions WHERE operator='Venture Travel') AS Prop 
WHERE routes.route_number 
  IN (SELECT route FROM operation_proportions WHERE operator='Venture Travel');

我得到的结果是: result

正如您所看到的,由于某些我无法弄清楚的原因,每个值被选中3次。我已经删除了sql语句的某些部分用于测试目的,因为我得到的结果不是预期的结果。

以下是我试图开始工作的完整陈述:

SELECT SUM((Prop.proportion / 100) * routes.frequency) AS TotalJourneys 
FROM routes, 
  (SELECT proportion FROM operation_proportions WHERE operator='Venture Travel') AS Prop 
WHERE routes.route_number 
  IN (SELECT route FROM operation_proportions WHERE operator='Venture Travel');

基本上我想要实现的是计算运营商所谓的Venture Travel每小时的总公交路线。比例是介于0到100之间的值(在这种情况下,只使用100和50,这不是问题),频率是公共汽车每小时完成路线的次数。

所以我的最终目标是用几句话:汇总Venture Travel运营的路线的每个频率*(比例/ 100)。

抱歉,我没有正确解释或错过了有用的数据,如果您需要更多信息来帮助我,请告诉我。感谢。

2 个答案:

答案 0 :(得分:1)

SUM()函数通常用于聚合环境。因此,我建议您打算为表中的每个路由号计算一些统计信息。这是我对你想要的东西的猜测:

SELECT r.route_number,
       SUM((o.proportion / 100) * r.frequency) AS TotalJourneys 
FROM routes r
INNER JOIN operation_proportions o
    ON r.route_number = o.route
GROUP BY r.route_number
WHERE o.operator = 'Venture Travel'

答案 1 :(得分:1)

内联视图Prop的原因是什么?根据观察到的行为的描述,我们怀疑内联视图查询

         SELECT proportion
           FROM operation_proportions
          WHERE operator = 'Venture Travel'

返回三行。并且这三行中的每一行都与从routes返回的每一行“匹配”。查询的结果是笛卡尔积...从routes返回的每一行都匹配到内联视图返回的每一行。

问题中的第一个查询可以等效地写为。

 SELECT r.route_number
      , r.frequency
   FROM routes r
  CROSS
   JOIN ( SELECT p.proportion 
            FROM operation_proportions p
           WHERE p.operator = 'Venture Travel'
        ) q
  WHERE r.route_number IN ( SELECT o.route 
                              FROM operation_proportions o
                             WHERE o.operator = 'Venture Travel'
                          )

我们可以取消对内联视图的连接,这样我们只能从routes得到每一行的一个副本......

SELECT r.route_number
     , r.frequency
  FROM routes r
 WHERE r.route_number IN ( SELECT o.route 
                             FROM operation_proportions o
                            WHERE o.operator = 'Venture Travel'
                         )

如果route列中operations_proportions列的值为operator = 'Venture Travel'中的UNIQUE,我们可以使用JOIN操作返回等效结果。

SELECT r.route_number
     , r.frequency
  FROM routes r
  JOIN operation_proportions o
    ON o.route = r.route_number
 WHERE o.operator = 'Venture Travel'

这将让我们从匹配的行返回proportion列的值,并将其包含在表达式中

 SELECT r.route_number
      , r.frequency
      , o.proportion
      , r.frequency * o.proportion / 100.0
   FROM routes r
   JOIN operation_proportions o
     ON o.route = r.route_number
  WHERE o.operator = 'Venture Travel'

然后我们可以使用聚合函数来“折叠”行以获得总计

 SELECT SUM( r.frequency * o.proportion / 100.0 ) AS TotalJourneys
   FROM routes r
   JOIN operation_proportions o
     ON o.route = r.route_number
  WHERE o.operator = 'Venture Travel'

如果route中的operation_proportions不是唯一的,我们可以解决这个问题。我们只需要确定是否要返回所有匹配的行,或者返回哪些行。