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?
The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:
ALTER TABLE `comments` ADD INDEX `comments_idx_match_id` (`match_id`);
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