Indexes

  • table scan visit each row in a table and inspect the contents which is property.
    • 检索速度和表的行数相关,当表的行数特别大时会导致检索的时间很长。

Index Creation

  • 已有的表格中添加Index: ALERT TABLE $tbl_name ADD INDEX $inx_name ($idx_field)
  • 此外,当创建Table时PRIMARY KEY ()KEY操作均会自动产生INDEX
  • 删除INDEX: ALERT TABLE $tbl_name DROP INDEX $idx_name

Unique indexes

  • 不允许Index中存在重复的数据
  • 添加Unique Index ALERT TABLE $tbl_name ADD UNIQUE $idx_name ($fld_name)

Multiple indexes

  • ALERT TABLE $tbl_name ADD INDEX $inx_name ($idx_field1, $idx_field2)
  • 组织顺序的影响:可以根据$idx_field1$idx_field2合并进行查询,也可以仅通过$idx_field1的值进行查询,但是无法根据$idx_field2进行查询,因此在构建之前,需要考虑实际的使用情况

Types of Indexes

B-tree Indexes

F%i

  • 适用于具有较多种类的情况,如个人姓名
Bitmap Indexes
  • 适用于仅有较少数据种类,但很多行都持有该种类 (low-cardinality),如性别
Text Indexes
  • 文本检索 full-text indexes

How Indexes Are Used

  • EXPLAIN 查看Server的运行情况,使用了那种方式来检索。tunning
    • 当存在Index时,Server会自动选择用Index来检索加快速度。

The Downside of Index

  • 每个Index其实都是一个Table

    • 执行速度:当一张表进行更改时,其他的Index也都需要更改,因此,过多的Indexes会减慢执行速度
    • 磁盘空间:Index还会占据一定的磁盘空间,因此,只有当真正需要的时候再设定Index。
      • 可以选择在需要的时候添加一个Index,用完之后就DROP,之后需要用的时候再ADD
  • 该如何设定合适的Index

    • PRIMARY KEY 必须是INDEXES,当为多列PRIMARY KEY时,可以考虑讲其中某一列设定为INDEX,或者以不同的顺序讲所有的列设定为新的INDEX
    • FOREIGN KEY 最好是INDEX,因为其是需要和参考的field进行对比,需要经常性的检索。
    • 常用的field 最好是INDEX。

results matching ""

    No results matching ""