mysql - MySQL select查询运行比较慢
问题描述
从我以前的帖子中,我发现如果我在选择查询中引用多个列,我需要一个复合索引,所以对于我的表
CREATE TABLE price (
dt TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
marketId INT,
buy DOUBLE,
sell DOUBLE,
PRIMARY KEY (dt, marketId),
FOREIGN KEY fk_price_market(marketId) REFERENCES market(id) ON UPDATE CASCADE ON DELETE CASCADE
) ENGINE=INNODB;
我创建了复合索引:
CREATE INDEX idx_price_market_buy ON price (marketId, buy, sell, dt);
现在查询
select max(dt) from price where marketId=309 and buy>0.3;
在 0.02 秒内执行得足够快,但是具有相同列组合的类似查询
select max(buy) from price where marketId=309 and dt>'2019-10-29 15:00:00';
需要 0.18 秒,相对较慢。
这些查询的描述看起来有点不同:
mysql> desc select max(dt) from price where marketId=309 and buy>0.3;
+----+-------------+-------+------------+-------+-----------------------------------------------------+----------------------+---------+------+-------+----------+--------------------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------+------------+-------+-----------------------------------------------------+----------------------+---------+------+-------+----------+--------------------------+
| 1 | SIMPLE | price | NULL | range | idx_price_market,idx_price_buy,idx_price_market_buy | idx_price_market_buy | 13 | NULL | 50442 | 100.00 | Using where; Using index |
+----+-------------+-------+------------+-------+-----------------------------------------------------+----------------------+---------+------+-------+----------+--------------------------+
1 row in set, 1 warning (0.00 sec)
mysql> desc select max(buy) from price where marketId=309 and dt>'2019-10-29 15:00:00';
+----+-------------+-------+------------+------+-----------------------------------------------+----------------------+---------+-------+--------+----------+--------------------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------+------------+------+-----------------------------------------------+----------------------+---------+-------+--------+----------+--------------------------+
| 1 | SIMPLE | price | NULL | ref | PRIMARY,idx_price_market,idx_price_market_buy | idx_price_market_buy | 4 | const | 202176 | 50.00 | Using where; Using index |
+----+-------------+-------+------------+------+-----------------------------------------------+----------------------+---------+-------+--------+----------+--------------------------+
1 row in set, 1 warning (0.00 sec)
例如, key_len 不同。这是什么意思?
buy
主要问题:和dt
列之间有什么区别?为什么在查询中切换它们会影响性能?
解决方案
推荐阅读
- c - 将函数的返回值存储为 C 中的结构体数组
- html - 如何从祖父母那里继承 CSS 属性
- spring - MongoTemplate 批量操作忽略限制
- ios - 添加一个信号目标后Flutter ios构建错误
- google-analytics - 使用 Google Analytics 联系表格 7 - gtag 事件跟踪(目标)
- sqlite - SQL 语法查询
- typescript - 如何检查泛型 K 是否属于泛型 M | 打字稿通用 | 还原
- r - 如何在r中编写以下公式?
- javascript - 输入数字时如何将数字从文本框自动复制到另一个文本框
- python - 从单词列表中提取所有匹配的关键字并创建一个新的数据框 pandas