Skip to content

Commit af3e988

Browse files
author
chengwei2
committed
update
1 parent e25e823 commit af3e988

File tree

1 file changed

+12
-0
lines changed

1 file changed

+12
-0
lines changed

_posts/2017-10-22-数据库索引技术.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,9 +186,21 @@ Index Selectivity = Cardinality / #T
186186

187187
显然选择性的取值范围为(0, 1],选择性越高的索引价值越大,这是由B+Tree的性质决定的。例如,上文用到的employees.titles表,如果title字段经常被单独查询,是否需要建索引,我们看一下它的选择性:
188188
![索引选择性与前缀索引](/img/database-index/database-index-22.png)
189+
189190
title的选择性不足0.0001(精确值为0.00001579),所以实在没有什么必要为其单独建索引。有一种与索引选择性有关的索引优化策略叫做前缀索引,就是用列的前缀代替整个列作为索引key,当前缀长度合适时,可以做到既使得前缀索引的选择性接近全列索引,同时因为索引key变短而减少了索引文件的大小和维护开销。下面以employees.employees表为例介绍前缀索引的选择和使用。可以看到employees表只有一个索引<emp_no>,那么如果我们想按名字搜索一个人,就只能全表扫描了:
190191
![索引选择性与前缀索引](/img/database-index/database-index-23.png)
191192

193+
如果频繁按名字搜索员工,这样显然效率很低,因此我们可以考虑建索引。有两种选择,建<first_name>或<first_name, last_name>,看下两个索引的选择性:
194+
![索引选择性与前缀索引](/img/database-index/database-index-24.png)
195+
显然<first_name>选择性太低,<first_name, last_name>选择性很好,但是first_name和last_name加起来长度为30,有没有兼顾长度和选择性的办法?可以考虑用first_name和last_name的前几个字符建立索引,例如<first_name, left(last_name, 3)>,看看其选择性:
196+
![索引选择性与前缀索引](/img/database-index/database-index-25.png)
197+
选择性还不错,但离0.9313还是有点距离,那么把last_name前缀加到4:
198+
![索引选择性与前缀索引](/img/database-index/database-index-26.png)
199+
这时选择性已经很理想了,而这个索引的长度只有18,比<first_name, last_name>短了接近一半,我们把这个前缀索引建上:
200+
![索引选择性与前缀索引](/img/database-index/database-index-27.png)
201+
此时再执行一遍按名字查询,比较分析一下与建索引前的结果:
202+
![索引选择性与前缀索引](/img/database-index/database-index-28.png)
203+
性能的提升是显著的,查询速度提高了120多倍。
192204

193205
> 前缀索引兼顾索引大小和查询速度,但是其缺点是不能用于ORDER BY和GROUP BY操作,也不能用于Covering index(即当索引本身包含查询所需全部数据时,不再访问数据文件本身)。
194206

0 commit comments

Comments
 (0)