I want to get latest records of the table with some settings_ids.
id | settings_id | added_date |
---|---|---|
1 | 7 | 2022-08-23 01:44:24 |
2 | 9 | 2022-08-23 01:44:24 |
3 | 11 | 2022-08-23 01:44:24 |
4 | 7 | 2022-08-25 01:44:24 |
5 | 9 | 2022-08-25 01:44:24 |
6 | 11 | 2022-08-25 01:44:24 |
7 | 7 | 2022-08-26 01:44:24 |
8 | 9 | 2022-08-26 01:44:24 |
9 | 11 | 2022-08-26 01:44:24 |
SELECT id, settings_id, MAX(added_date)
FROM data_rows
WHERE settings_id IN (7,9,11)
GROUP BY settings_id;
Expected Result
id | settings_id | added_date |
---|---|---|
7 | 7 | 2022-08-26 01:44:24 |
8 | 9 | 2022-08-26 01:44:24 |
9 | 11 | 2022-08-26 01:44:24 |
I am getting the result I want but the thing is it taking more than a minute to get the data.
Is there a way to reduce the time taken by this query?
Thanks
2
Answers
On MySQL 8+, your requirement is easily met using
ROW_NUMBER
:As for optimizing the above query, an index on
(settings_id, dateAdded DESC)
should help:This index, if used, should let MySQL rapidly compute the required row number.
Edit:
On MySQL 5.7, use this query:
Use the same index as suggested above.
Be aware that you won’t necessarily get the
id
that matches theMAX
. Cf "only_full_group_by".For this (no
id
):Simply have
INDEX(settings_id, added_date)
For also getting the matching
id
, see thegroupwise max
tag. Or ids — there could be dup dates?If there are no dup dates (and you want
id
), thenAt that point, do you really need
id
? Consider getting rid ofid
and changing to(and going back to my first SELECT suggestion)
Do note that a "composite" (multi-column) index is not the same as separate indexes on each column.