I have following query which returns most recent records (grouped) from a table keeping history of devices; FIELD_A being a serial number; DateFIELD_B being a date, one record a day per device.
Only most recent occurrence per device interests me but it is not necessarily the same date for all devices.
SELECT t1.*
FROM TABLE_A t1
WHERE t1.DateFIELD_B = (SELECT MAX(t2.DateFIELD_B)
FROM TABLE_A t2
where t2.FIELD_A = t1.FIELD_A
group by FIELD_A);
Query works fine as such (when limiting for test to a few specific serials) but fails due a timeout when using full range. Table has 4,75 millions records. Fields are indexed.
Would you have some advice to optimize this ?
Thank you,
2
Answers
For MySQL 5.x:
For MySQL 8+:
The index by
(field_a, datefield_b)
must improve.Try