如何索引以避免全表扫描?

时间:2012-09-27 06:18:18

标签: mysql optimization indexing

如何索引以下查询以避免全表扫描?

explain SELECT fld1, fld2 FROM tablename WHERE IdReceived > 0; 

+----+-------------+------------------+------+---------------+------+---------+------+-------+-------------+
| id | select_type | table            | type | possible_keys | key  | key_len | ref  | rows  | Extra       |
+----+-------------+------------------+------+---------------+------+---------+------+-------+-------------+
|  1 | SIMPLE      | tablename        | ALL  |IdReceived _idx| NULL | NULL    | NULL | 99617 | Using where | 
+----+-------------+------------------+------+---------------+------+---------+------+-------+-------------+

我已经修改了查询,然后我也可以看到行id2(UNION)进行全表扫描。

explain SELECT fld1,fld2 FROM tablename WHERE IdReceived=1 UNION SELECT fld1,fld2 FROM tablename WHERE IdReceived>=1;
+----+--------------+------------------+------+---------------+--------------+---------+-------+-------+-------------+
| id | select_type  | table            | type | possible_keys | key          | key_len | ref   | rows  | Extra       |
+----+--------------+------------------+------+---------------+--------------+---------+-------+-------+-------------+
|  1 | PRIMARY      | tablename | ref  | IdReceived _idx  | IdReceived _idx | 4       | const |  8865 |             | 
|  2 | UNION        | tablename | ALL  | IdReceived _idx  | NULL         | NULL    | NULL  | 99617 | Using where | 
| NULL | UNION RESULT | <union1,2>       | ALL  | NULL          | NULL         | NULL    | NULL  |  NULL |             | 
+----+--------------+------------------+------+---------------+--------------+---------+-------+-------+-------------+

1 个答案:

答案 0 :(得分:0)

由于您要将索引列与常量值进行比较,请尝试避免这种情况。

请参阅此处:http://dev.mysql.com/doc/refman/5.0/en/where-optimizations.html

另外我建议fld1上的非聚集索引,fld2使这个查询执行得更快