1

我有以下查询:

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

4

1 回答 1

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 保持相同的结果)

于 2013-03-18T12:52:24.007 回答