mysql - 如何优化此选择位置和“日期时间”sql?
问题描述
我有一个查询,它记录在 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
非常感谢!
解决方案
对于此查询:
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)
.
推荐阅读
- python-3.x - 从云函数连接到云 sql 时出现 Python 错误
- laravel - 为什么我们要在 Laravel Sanctum 上调用 sanctum/csrf-cookie
- python - “您的程序中有错误:扫描单引号时 EOL”python 2.5 需要帮助来解决此代码
- python - NEO4J MATCH 查询返回不正确的输出
- css - Next.js 配置破坏了包的 CSS
- javascript - 如何及时获取今天的日期+ 00:00:00
- r - 当您在 R 中混合使用数字和字符时如何舍入?
- java - Java 在执行 Callable 之前等待变量
- azure-devops - 在 azure devops 中设置项目头像的 PAT 范围有哪些?
- ios - 使用 UIPencilKit 预定义的形状