嵌套GROUP BY优化

时间:2013-03-18 12:48:48

标签: mysql sql sql-optimization

我有以下查询:

SELECT trip_id, MAX(cnt) FROM 
(
    SELECT trip_id, stop_id, COUNT(*) as cnt 
    FROM operation_ticket_part_stops 
    GROUP BY trip_id, stop_id
) AS t
GROUP BY trip_id

结果是(这是我想要的结果):

trip_id MAX(cnt)
10072 2
10583 1
**10607 11**
10608 8
10609 13
10612 5
11170 1
11239 1
11675 30
...

子查询的结果是:

trip_id stop_id cnt
...
10607 11234 11
10607 11235 10
10607 11236 10
10607 11237 11
10607 11238 9
10607 11239 7
...

我有什么方法可以避免这里的子查询(并优化可能?)。数据库:MySQL

1 个答案:

答案 0 :(得分:2)

像这样的东西

SELECT trip_id, stop_id, COUNT(*) as cnt 
FROM operation_ticket_part_stops 
GROUP BY trip_id, stop_id
ORDER BY cnt DESC
LIMIT 1

此查询对您的子查询进行排序并仅获取第一条记录(其结果与Max相同)