SQL如下:
select u.uid,u.cid,u.username,u.loginNum,u.flag from username as u where u.loginNum > 0 and u.flag ='0' and (u.cid = 796 or u.uid = '796') order by u.uid
已经在uid,cid,flag字段添加索引.
但explain显示还是全索引扫描.
----+-------------+-------+-------+---------------------------------+---------+---------+------+------+-------------+
| id | select_type | table | type  | possible_keys                   | key     | key_len | ref  | rows | Extra       |
+----+-------------+-------+-------+---------------------------------+---------+---------+------+------+-------------+
|  1 | SIMPLE      | u     | index | PRIMARY,uid,cid,flag,user_index | PRIMARY | 4       | NULL | 3470 | Using where |
+----+-------------+-------+-------+---------------------------------+---------+---------+------+------+-------------+

解决方案 »

  1.   

    你怎么判断是全索引扫描.?从EXPLAIN结果来看,是用到索引的
      

  2.   

    应该建立uid和cid的联合索引才行
    alter table username  add index(uid,cid)因为你里面是or的关系
      

  3.   

    select u.uid,u.cid,u.username,u.loginNum,u.flag from username as u where u.loginNum > 0 and u.flag ='0' and u.cid = 796 order by u.uid
    union all
    select u.uid,u.cid,u.username,u.loginNum,u.flag from username as u where u.loginNum > 0 and u.flag ='0' and u.uid = 796 order by u.uid
    把cid上的索引改成 cid和uid的多列索引idx_cuid(cid,uid)
      

  4.   

    从执行计划来看已经用到了索引,但现在索引不是用到的联合
    索引(cid,uid)
      

  5.   

    当MYSQL认为一个列中符合条件的值大于30%时,MYSQL就会认为索引的效率不高,会使用全表扫描。
    你可以show index from username 观察一下索引的分布。