【发布时间】:2011-04-30 02:57:23
【问题描述】:
表结构:
+-------------+----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+----------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| total | int(11) | YES | | NULL | |
| thedatetime | datetime | YES | MUL | NULL | |
+-------------+----------+------+-----+---------+----------------+
总行数:137967
mysql> explain select * from out where thedatetime <= NOW();
+----+-------------+-------------+------+---------------+------+---------+------+--------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------------+------+---------------+------+---------+------+--------+-------------+
| 1 | SIMPLE | out | ALL | thedatetime | NULL | NULL | NULL | 137967 | Using where |
+----+-------------+-------------+------+---------------+------+---------+------+--------+-------------+
真正的查询要长得多,有更多的表连接,关键是,我无法让表使用datetime 索引。如果我想在某个日期之前选择所有数据,这对我来说会很困难。但是,我注意到如果我选择较小的数据子集,我可以让 MySQL 使用索引。
mysql> explain select * from out where thedatetime <= '2008-01-01';
+----+-------------+-------------+-------+---------------+-------------+---------+------+-------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------------+-------+---------------+-------------+---------+------+-------+-------------+
| 1 | SIMPLE | out | range | thedatetime | thedatetime | 9 | NULL | 15826 | Using where |
+----+-------------+-------------+-------+---------------+-------------+---------+------+-------+-------------+
mysql> select count(*) from out where thedatetime <= '2008-01-01';
+----------+
| count(*) |
+----------+
| 15990 |
+----------+
那么,我该怎么做才能确保无论我输入什么日期,MySQL 都会使用索引?
【问题讨论】:
-
EXPLAIN告诉您索引已“使用”,或者更准确地说,它已考虑 - 在这两种情况下。我在下面的回答详细解释了。另一方面,如果您遇到表现不佳,那么您就过于简化了问题。
标签: mysql database-design