简体   繁体   English

mysql:奇怪的错误1111无效使用group by

[英]mysql: strange error 1111 invalid use of group by

Following is a query i am trying to run. 以下是我试图运行的查询。

select location_data.trip_code,sum(max(device_time)-min(device_time)) from location_data,trip_management 
where location_data.source_id=3 and location_data.trip_code=trip_management.trip_code
group by location_data.trip_code

there are various trips identified by trip_code in both trip_managemnet and location_data tables.these trips are taken by a single uniquely identified user (source_id=)3. trip_managemnet和location_data表中的trip_code标识了各种行程。这些行程由单个唯一标识的用户(source_id =)3进行。 what i am trying to do here is to sum all the time differences for each trip and then convert it into hh:mm:ss using the sec_to_time function to display the total time it took user 3 to take all of his trips. 我在这里尝试做的是总结每次旅行的所有时间差异,然后使用sec_to_time函数将其转换为hh:mm:ss,以显示用户3完成所有旅行所花费的总时间。

the problem with above query is that it generates error 1111 as soon as i apply sum() over the difference of max and min device_time of each trip. 上面的查询的问题是,一旦我对每次旅行的最大和最小device_time的差异应用sum(),它就会生成错误1111。 i cant afford a subquery because this in itself is a subquery in a larger query. 我不能提供子查询,因为这本身就是一个更大的查询中的子查询。

I hope i explained the problem well. 我希望我能很好地解释这个问题。

The issue here is that you are attempting to apply an aggregate SUM() over the aggregates MAX(),MIN() , but in fact the two levels operate on different groups. 这里的问题是你试图在聚合MAX(),MIN()上应用聚合SUM() MAX(),MIN() ,但实际上这两个级别在不同的组上运行。 The inner one groups over location_data.trip_code , and the outer one groups over the result of that. 内部组合在location_data.trip_code ,外部组合在其结果上。 You'll need to wrap it in a subquery: 你需要将它包装在子查询中:

SELECT
  trip_code,
  /* Outer query sums the inner aggregates */
  SUM(max_time - min_time) AS time_sum
FROM (
  SELECT 
    location_data.trip_code,
    /* Inner aggregates return the max & min times only */
    max(device_time) AS max_time,
    min(device_time) AS min_time
  FROM
     location_data,
     INNER JOIN trip_management ON location_data.trip_code = trip_management.trip_code
  WHERE
     location_data.source_id=3
  GROUP BY location_data.trip_code
) first_group
GROUP BY trip_code

I've also replaced you implicit join with an explicit INNER JOIN , which is the preferred syntax nowadays. 我还用一个显式的INNER JOIN替换了你的隐式连接,这是现在的首选语法。

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

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