Home > Database > Mysql Tutorial > mysql前缀索引_MySQL

mysql前缀索引_MySQL

WBOY
Release: 2016-06-01 13:36:16
Original
977 people have browsed it

bitsCN.com

mysql前缀索引

 

应用场景:

数据库里有个地址(address)字段,类型为varchar(100),业务决定了要经常根据
address来进行查询。    

确定选择性:

Sql代码  

SELECT count(DISTINCT(address))/count(*) AS Selectivity FROM info;    

+-------------+     

| Selectivity |    

+-------------+     

|      0.8745 |    

+-------------+    

 

选择性很好,但是长度为100,对整个字段建立索引显然不合适,可以考虑建立
前缀索引,例如,看看其选择性:    

Sql代码  

SELECT count(DISTINCT(left(address,5)))/count(*) AS Selectivity FROM info;    

+-------------+     

| Selectivity |    

+-------------+     

|      0.5981 |    

+-------------+     

 

选择性还不错,但和0.8745相比还是太低,所以我们可以将前缀长度增加到10,再看看
选择性:    

Sql代码  

SELECT count(DISTINCT(left(address,10)))/count(*) AS Selectivity FROM info;    

+-------------+     

| Selectivity |    

+-------------+     

|      0.8239 |    

+-------------+    

 

和0.8745已经很接近了,但是索引长度只有10,所以就可以决定建立前缀索引了。

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

 

bitsCN.com
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template