Heim  >  Artikel  >  Datenbank  >  B+树索引的使用

B+树索引的使用

WBOY
WBOYOriginal
2016-06-07 17:30:18921Durchsuche

可以看到我们将取出行的数大概是表的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: 

linux

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn