1

我使用具有以下创建的大型(> 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。

我需要有关如何加快查询速度的建议,

多谢。

4

1 回答 1

0

你有一个关于 的索引(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) ;
于 2013-01-25T11:09:00.850 回答