数据库索引

2018-01-08  本文已影响19人  mualex

索引是用来迅速定位并且找到特定的数据集。 如果没有索引, 数据库会从头遍历整个表, 采用索引的情况下, 数据库可以从数据中端定位并且开始寻找需要的数据集。

聚集索引 Cluster Index

根据真实地址存储和排序(asc/desc), 每个表中只能有一个Cluster Index. 只有Cluster Index 被创建了以后, 表中数据才会依据排序后的顺序存储。否则表中存储数据的结构在无序的堆中。

索引的叶结点是数据节点

非聚集索引 Nonclustered Index

索引的叶结点是索引节点, 保存一个指针指向数据块

最左匹配
(col1), (col1, col2), and (col1, col2, col3) 可以hit到
(col1, col2, col3) index

B树索引

B-tree index 会在以下操作生效:
=, > , >=, <, <=, BETWEEN, LIKE (1. 只能应用于不以%开头的字符串常量)

SELECT * FROM tbl_name WHERE key_col LIKE 'Patrick%';    (hit)
SELECT * FROM tbl_name WHERE key_col LIKE 'Pat%_ck%'; 

'Pat' <= key_col < 'Pau' 只有这样的才会用到索引

SELECT * FROM tbl_name WHERE key_col LIKE '%Patrick%';   前% 不会用到索引
SELECT * FROM tbl_name WHERE key_col LIKE other_col;     非字符串常量,不会用到索引

以下成功应用索引

... WHERE index_part1=1 AND index_part2=2 AND other_column=3
    index = 1 OR index = 2 
... WHERE index=1 OR A=10 AND index=2
    optimized like "index_part1='hello'" 
... WHERE index_part1='hello' AND index_part3=5
    Can use index on index1 but not on index2 or index3 
... WHERE index1=1 AND index2=2 OR index1=3 AND index3=3;

以下不会应用索引

    index_part1 is not used 
... WHERE index_part2=1 AND index_part3=2
    index is not used in both parts of the WHERE clause  
... WHERE index=1 OR A=10
    No index spans all rows
... WHERE index_part1=1 OR index_part2=10

Hash 索引
只生效与 = 或者 <> , 速度很快

上一篇下一篇

猜你喜欢

热点阅读