可以看到我们将取出行的数大概是表的100%的行,因此优化器没有选择使用索引。mysql数据库的优化器会通过explain的rows字段预估查
什么时候使用b+树索引
并不是在所有的查询条件下出现的列都需要添加索引。对于什么时候添加b+树索引,我的经验是访问表中很少一部分时,使用b+树索引才有意义。对于性别字段,地区字段,类型字段,它们可取值的范围很小,即低选着性。如:
select * from student where sex = 'm'
对于性别,可取值的范围只有'm','f'。对上述sql语句得到的结果可能是该表的50%的数据,这时添加b+树索引时完全没有必要的。相反,如果某个字段的取值范围很广,几乎没有重复,即高选择性,即此时使用b+树索引时做合适的,例如姓名字段,基本上在一个应用中都不允许重名的出现。
因此,当访问高选择性字段并从表中取出很少一部分时,对这个字段添加b+树索引是非常有必要的。但是如果出现了访问字段是高选择性的,但是取出的行数据占用表中大部分的数据时,这时mysql数据库就不会使用b+树索引了,我们先来看一个例子:
mysql> show index from info\g;
*************************** 1. row ***************************
table: info
non_unique: 0
key_name: primary
seq_in_index: 1
column_name: id
collation: a
cardinality: 356639
sub_part: null
packed: null
null:
index_type: btree
comment:
index_comment:
*************************** 2. row ***************************
table: info
non_unique: 1
key_name: index_link_family
seq_in_index: 1
column_name: link_family
collation: a
cardinality: 9385
sub_part: 255
packed: null
null: yes
index_type: btree
comment:
index_comment:
*************************** 3. row ***************************
table: info
non_unique: 1
key_name: index_date
seq_in_index: 1
column_name: date
collation: a
cardinality: 356639
sub_part: null
packed: null
null:
index_type: btree
comment:
index_comment:
,