[Solved] How to get the value of a row with Max aggregation function?
Looking to automatically optimize YOUR SQL query? Start for free.

EverSQL Database Performance Knowledge Base

How to get the value of a row with Max aggregation function?

I have a table for comments :

+----------+---------------------+----------+
| match_id |     timestampe      | comment  |
+----------+---------------------+----------+
|      100 | 2014-01-01 01:00:00 | Hi       |
|      200 | 2014-01-01 01:10:00 | Hi1      |
|      300 | 2014-01-01 01:20:00 | Hi2      |
|      100 | 2014-01-01 01:01:00 | Hello    |
|      100 | 2014-01-01 01:02:00 | Hello1   |
|      200 | 2014-01-01 01:11:00 | hey      |
+----------+---------------------+----------+

I want to get the following information from the table

SELECT match_id, max(timestampe) as maxtimestamp, count(match_id) as comments_no
FROM comments
GROUP BY match_id
order by maxtimestamp DESC

The previous explanation is working great but the problem is when I want to get the comment of the maxtimestamp.

How can I get the latest comment of each match (the comment of the maxtimestamp) using the most optimized query?

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
Optimal indexes for this query:
ALTER TABLE `comments` ADD INDEX `comments_idx_match_id` (`match_id`);
The optimized query:
SELECT
        comments.match_id,
        max(comments.timestampe) AS maxtimestamp,
        count(comments.match_id) AS comments_no 
    FROM
        comments 
    GROUP BY
        comments.match_id 
    ORDER BY
        maxtimestamp DESC

Related Articles



* original question posted on StackOverflow here.