[英]How to index to avoid full table scan?
如何为以下查询建立索引以避免全表扫描?
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 | |
+----+--------------+------------------+------+---------------+--------------+---------+-------+-------+-------------+
由于您正在将索引列与常量值进行比较,因此请避免这种情况。
请参阅此处: http : //dev.mysql.com/doc/refman/5.0/en/where-optimizations.html
另外,我建议在fld1,fld2上使用non_clustered索引,以使此查询执行得更快
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.