表tbl有2个相同类型的字段cola,colb,类型都是smallint。
我建立了这2个字段的复合索引list。执行sql1:
EXPLAIN SELECT * 
FROM `tbl` 
WHERE cola >=32 AND colb <=33 
ORDER BY colaexplain的结果是使用了list索引。但是执行sql2:
EXPLAIN SELECT * 
FROM `tbl` 
WHERE cola >=2 AND colb <=30 
ORDER BY colaexplain的结果确说没有使用索引,
+----+-------------+-------+------+---------------+------+---------+------+-----
-+-----------------------------+
| id | select_type | table | type | possible_keys | key  | key_len | ref  | rows
 | Extra                       |
+----+-------------+-------+------+---------------+------+---------+------+-----
-+-----------------------------+
|  1 | SIMPLE      | node  | ALL  | treelist      | NULL | NULL    | NULL |   17
 | Using where; Using filesort |
+----+-------------+-------+------+---------------+------+---------+------+-----
搞不懂为什么会这样,按理说这2个sql应该是一样的,只是查询范围不同而已
请大家帮忙解答。

解决方案 »

  1.   

    另外想问问sql2的explain结果,既然key列为空,为什么extra列会出现using where呢?
    还有就是extra列为什么会有2个结果using where和using filesort?
      

  2.   

    贴出你的 show index from `tbl`  
      

  3.   

    Table  Non_unique  Key_name  Seq_in_index  Column_name  Collation  Cardinality  Sub_part  Packed  Null  Index_type  Comment  
    tbl 0 PRIMARY 1 id A 17 NULL NULL   BTREE   
    tbl 0 list 1 cola A 17 NULL NULL   BTREE   
    tbl 0 list 2 colb A 17 NULL NULL   BTREE   
      

  4.   

    你的表中不过才17个记录,并且cola的值都不同。
    这样你的WHERE cola >=32 AND colb <=33 这个条件下,复合索引并无实际意义,其作用不过等同于一个(cola)的索引。也就是仅 WHERE cola >=32利用了到list(cola,colb)的cola索引部分。
    当你WHERE cola >=2 时,根据索引统计信息,几乎你所有的17条记录均符合这个 cola >=2,这样情况下使用索引已经毫无疑义。