I have a currency rate database and want to select only the most recent rates by having a timestamp defining the recentness. (Selecting the most recent one per rate, not over all as they could have different timestamps)
The following query does what I want, but is super slow (>3 seconds)
SELECT cR.currencyCode, cR.rate, cR.timestamp FROM currentRates cR
JOIN ( SELECT MAX(timestamp) as max, currencyCode
FROM currentRates
GROUP BY currencyCode) cR_mt
ON (cR.timestamp = cR_mt.max AND cR.currencyCode = cR_mt.currencyCode);
The table Schema is as following:
CREATE TABLE `currentRates` (
`ID` int(11) NOT NULL,
`rate` float DEFAULT NULL,
`currencyCode` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`timestamp` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
With there being currently ~ 150k entries.
Could you please help me with your knowledge to improve the time of the query. I already did an index on rate and currencyCode and got down to 3 seconds (before it took ~10 seconds)
Thanks so much for your help!
L1am0