在mysql中,对于索引的使用并是一直都采用正确的决定。
简单表的示例:
create table `r2` (
id` int(11) default null,
id1` int(11) default null,
cname` varchar(32) default null,
key `id1` (`id1`)
) engine=myisam default charset=latin1
select count(*) from r2;
250001 (v1)
select count(*) from r2 where id1=1;
83036 (v2)
(execution time = 110 ms)
(id1=1)条件查询索引的选择性是 v2/v1 = 0.3321 或 33.21%
一般来说(例如书 “sql tuning“),如果选择性超过 20% 那么全表扫描比使用索引性能更优。
我知道oracle一直是在选择性超过25%时会选择全表扫描。
而mysql呢:
mysql> explain select count(subname) from r2 where id1=1;
+----+-------------+-------+------+---------------+-----
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | extra |
+----+-------------+-------+------+---------------+-----
| 1 | simple | t2 | ref | id1 | id1 | 5 | const | 81371 | using where |
+----+-------------+-------+------+---------------+-----
这就是mysql将会使用索引来完成这个查询。
让我们来对比索引查询和全表扫描的执行时间:
select count(subname) from t2 where id1=1 - 410 ms
select count(subname) from t2 ignore index (id1) where id1=1 - 200 ms
如你所看到全表扫描要快2倍。
参考更特殊的例子:选择性 ~95%:
select cnt2 / cnt1 from (select count(*) cnt1 from r2) d1, (select count(*) cnt2 from r2 where id1=1) d2;
0.9492 = 94.92%;
说明mysql将会用索引来完成查询。
执行时间:
select count(subname) from t2 where id1=1 - 1200 ms
select count(subname) from t2 ignore index (id1) where id1=1 - 260 ms
这次全表扫描要快4.6倍。
为什么mysql选择索引访问查询?
mysql没有计算索引的选择性,只是预测逻辑io操作的数量,并且我们的例子中间的逻辑io数量,索引访问要少于全表扫描。
最后我们得出结论,对于索引要小心使用,因为它们并不能帮助所有的查询
