我有一个货币汇率数据库,并且想通过定义当前时间的时间戳来仅选择最新汇率。 (请为每个速率选择最新的速率,而不是全部,因为它们可能具有不同的时间戳)

以下查询可以满足我的要求,但是速度非常慢(> 3秒)

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);




表模式如下:

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;


目前有约15万个条目。



您能否以您的知识帮助我,以缩短查询时间。我已经对rate和currencyCode进行了索引,并降低到3秒(之前花了大约10秒)

非常感谢你的帮助!

L1am0

最佳答案

您正在按currencyCode分组并计算最大timestamp,因此索引应按该顺序为currencyCode, timestamp

CREATE INDEX IDX_currentRates_CurrencyCode_Timestamp ON currentRates (currencyCode, timestamp)

关于mysql - 查询优化以查找最新条目,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51287911/

10-11 02:45