Search code examples
mysqlsqlsql-optimization

Nested GROUP BY optimization


I have the following query:

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

Result is (this is the result I want):

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

Result for subquery is:

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

Is there any way I can avoid subquery here (and optimize maybe?). Database: MySQL


Solution

  • Something like this

    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
    

    This query sorts your sub query and takes the first record only (which holds the same result as the Max)