[英]mysql index seems to fail in large table
我使用具有以下創建內容的大型(> 1億行)表:
data_values | CREATE TABLE `data_values` (
`T` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`ID` varchar(32) NOT NULL,
`VAL` float DEFAULT NULL,
PRIMARY KEY (`T`,`ID`),
KEY `IX_d` (`ID`),
KEY `IX_T` (`T`)
) ENGINE=InnoDB DEFAULT CHARSET=greek PACK_KEYS=1 ROW_FORMAT=DYNAMIC |
我的查詢具有以下形式:
select t,id,val from data_values where t between "2013-01-11 02:47:02" and "2013-01-12 04:59:02" and id="815";
我的問題是有時使用索引(答案很快),有時不使用索引(答案在1-2分鍾之內),而我卻找不到任何邏輯。 例如,以下查詢很快:
select t,id,val from data_values where t between "2013-01-11 02:47:02" and "2013-01-13 04:59:02" and id="815";
而以下查詢(所需的數據較少,一天而不是兩天)很慢:
select t,id,val from data_values where t between "2013-01-11 02:47:02" and "2013-01-12 04:59:02" and id="815";
解釋查詢:
explain select t,id,value from data_values where t between "2013-01-11 02:47:02" and "2013-01-13 04:59:02" and id="815";
| id | select_type | table | type | possible_keys
| key | key_len | ref | rows | Extra
|
+----+-------------+----------------------+-------------+-----------------------
+-----------------+---------+------+------+-------------------------------------
----------+
| 1 | SIMPLE | data_values | index_merge | PRIMARY,IX_D,IX_T
| IX_D,PRIMARY | 34,38 | NULL | 1033 | Using intersect(IX_D,PRIMARY); Us
ing where |
+----+-------------+----------------------+-------------+-----------------------
+-----------------+---------+------+------+-------------------------------------
explain select t,id,val from data_values where t between "2013-01-11 02:47:02" and "2013-01-12 04:59:02" and id="815";
+----+-------------+----------------------+------+-----------------------+------
---+---------+-------+--------+-------------+
| id | select_type | table | type | possible_keys | key
| key_len | ref | rows | Extra |
+----+-------------+----------------------+------+-----------------------+------
---+---------+-------+--------+-------------+
| 1 | SIMPLE | data_values | ref | PRIMARY,IX_D,IX_T | IX_D | 34 | const | 143900 | Using where |
+----+-------------+----------------------+------+-----------------------+------
---+---------+-------+--------+-------------+
我不明白第一個查詢是“更廣泛”(請求更多數據)如何使用索引,而第二個查詢則不使用索引。 搜索stackoverflow我已經找到了有關多列索引的一些答案。 但是我已經使用了一個(我的主鍵),並且以正確的順序使用(在查詢中,在id前面提到了t變量)。 我發現的另一個答案與使用OR的查詢有關(執行單獨的查詢並形成UNION),但我的查詢使用AND。
我需要有關如何加快查詢速度的建議,
非常感謝。
您在(t, id)
上有一個索引。
您需要在(id, t)
上建立索引以進行此類查詢,甚至更好的是,在(id, t, val)
上建立“覆蓋”索引:
ALTER TABLE data_values
DROP INDEX IX_T -- the Primary Key is (t, id) so this index
-- is rather redundant.
, DROP INDEX IX_d -- this was not redundant but it is now
-- (because of)
, ADD INDEX IX_ID_T_VAL -- the new index
(id, t, value) ;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.