0

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

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 |             | 
+----+--------------+------------------+------+---------------+--------------+---------+-------+-------+-------------+
4

1 回答 1

0

由于您正在将索引列与常量值进行比较,因此请尽量避免这种情况。

参考这里:http ://dev.mysql.com/doc/refman/5.0/en/where-optimizations.html

另外我建议在 fld1,fld2 上使用非聚集索引,以使此查询执行得更快

于 2012-09-27T06:19:37.293 回答