我有一个查询,该查询已记录在mysql慢日志文件中:
# Time: 2019-06-12T10:23:05.410474Z
# User@Host: coi[coi] @ [172.31.ip.ip] Id: 91
# Query_time: 7.099090 Lock_time: 0.000065 Rows_sent: 0 Rows_examined:
844952
use coi;
SET timestamp=1560334985;
SELECT `trades`.* FROM `trades`
WHERE `trades`.`market_id` = 'omgeth'
AND (created_at > '2019-06-11 18:22:58.310183')
ORDER BY price
LIMIT 1;
在此,如何优化此查询?将索引添加到“ market_id和created_at”列?
该查询为什么检查844952条记录?如果我仅将索引添加到“ created_at”列怎么办?这会有所帮助吗?
这是我的表结构:
(this create table SQL comes from the "show create table" command)
CREATE TABLE `trades` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`price` decimal(32,16) DEFAULT NULL,
`market_id` varchar(10) DEFAULT NULL,
`created_at` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `index_trades_on_created_at` (`created_at`) USING BTREE,
KEY `index_trades_on_market_id` (`market_id`),
KEY `index_trades_on_price` (`price`),
) ENGINE=InnoDB AUTO_INCREMENT=3509954 DEFAULT CHARSET=utf8
非常感谢!
答案 0 :(得分:2)
对于此查询:
SELECT t.*
FROM `trades` t
WHERE t.`market_id = 'omgeth' AND
t.created_at > '2019-06-11 18:22:58.310183'
ORDER BY t.price
LIMIT 1;
您要在trades(market_id, created_at)
上建立索引。