日期:2014-05-16  浏览次数:20689 次

索引的使用时机与执行成本的问题--------mysql学的好累啊
表t1: create table t1(x int, y int, key i1 using btree(x)) engine=innodb

共42942条数据

describe select * from t1 where x<>40000 and x<2953
1 SIMPLE t1 range i1 i1 5 5896 Using where


describe select * from t1 where x<>40000 and x<2954
1 SIMPLE t1 ALL i1 39261 Using where


为什么会存在2953使用索引并且range查找, 而2954不使用索引并且全表扫描??? 如果这是查询优化器基于成本考虑的, 考虑的因素是什么, 各位大哥有无资料共享给小弟一下, 不胜感激



------------------------------------------------------------
另外据说btree是不支持<>比较的

describe select x from t1 where x<>5
1 SIMPLE t1 range i1 i1 5 19633 Using where; Using index
为什么能够使用索引进行范围查找, 这个是不是索引覆盖的原因



describe select * from t1 where x<>5
1 SIMPLE t1 ALL i1 39261 Using where
无论如何都是全表扫描, 

这两条语句, 是基于什么样的成本考虑才有如此不同的行为, 望大牛详解



------解决方案--------------------
慢慢来 学会了其实很简单
------解决方案--------------------
你的表中一共多少记录? 

如果符合条件的百分比大于一定数字,则MYSQL就直接使用全表扫描而不是通过索引了。