TIMESTAMP字段上的MYSQL索引不使用索引进行范围查询

时间:2013-12-24 17:43:12

标签: mysql indexing

我在mysql表中有以下行

+--------------------------------+----------------------+------+-----+---------+----------------+
| Field                          | Type                 | Null | Key | Default | Extra          |
+--------------------------------+----------------------+------+-----+---------+----------------+
| created_at                     | timestamp            | YES  | MUL | NULL    |                |

字段

上存在以下索引
*************************** 6. row ***************************
        Table: My_Table
   Non_unique: 1
     Key_name: IDX_My_Table_CREATED_AT
 Seq_in_index: 1
  Column_name: created_at
    Collation: A
  Cardinality: 273809
     Sub_part: NULL
       Packed: NULL
         Null: YES
   Index_type: BTREE
      Comment: 
Index_comment:

我正在尝试优化以下查询以使用范围条件的IDX_My_Table_CREATED_AT索引

SELECT * FROM My_Table as main_table  WHERE ((main_table.created_at >= '2013-07-01 05:00:00') AND (main_table.created_at <= '2013-11-09 05:59:59'))\G

当我在select查询中使用EXPLAIN时,我得到以下内容:

+----+-------------+------------+------+---------------------------------+------+---------+------+--------+-------------+
| id | select_type | table      | type | possible_keys                   | key  | key_len | ref  | rows   | Extra       |
+----+-------------+------------+------+---------------------------------+------+---------+------+--------+-------------+
|  1 | SIMPLE      | main_table | ALL  | IDX_My_Table_CREATED_AT         | NULL | NULL    | NULL | 273809 | Using where |
+----+-------------+------------+------+---------------------------------+------+---------+------+--------+-------------+

问题是IDX_My_Table_CREATED_AT索引未用于此范围条件,即使它是BTREE索引,因此应该适用于查询。

奇怪的是,如果我在列上尝试单个值查找,则使用索引。

EXPLAIN SELECT * FROM My_Table as main_table  WHERE (main_table.created_at = '2013-07-01 05:00:00');
+----+-------------+------------+------+---------------------------------+---------------------------------+---------+-------+------+-------------+
| id | select_type | table      | type | possible_keys                 | key                           | key_len | ref   | rows | Extra       |
+----+-------------+------------+------+---------------------------------+---------------------------------+---------+-------+------+-------------+
|  1 | SIMPLE      | main_table | ref  | IDX_My_Table_CREATED_AT index | IDX_My_Table_CREATED_AT index | 5       | const |    1 | Using where |
+----+-------------+------------+------+---------------------------------+---------------------------------+---------+-------+------+-------------+

为什么索引不用于范围条件?我已经尝试将查询更改为使用BETWEEN,但这并未改变任何内容。

1 个答案:

答案 0 :(得分:9)

答案很简单..

MySQL优化器是基于成本的,优化器计算出全表扫描是获取记录的最佳方式(最便宜)。

因为所需的范围看起来像是查看行(EXPLAIN)和基数的完整表格。这些数字相等。

如果MySQL优化器确实使用索引,相对成本会高得多,因为随机读取(慢)查找记录所需的内容

关于故事的座右铭在这种情况下,全表扫描不是世界末日......只是接受它......