添加字符串索引和前缀索引
添加字符串索引: alter table SUser add index index1(email);
在索引index1中包含每条记录的整个字符串
添加前缀索引:alter table SUser add index index2(email(6));
在index2 中对于每条记录只取前6字节
使用前缀索引的缺点和优点
缺点: 前缀索引可能会增加扫描行数,因为在前缀索引中前n个字节相同的情况下越少,扫描行数就少
优点: 也就是说使用前缀索引,定义好长度,就可以做到既节省空间,又不用额外增加太多的查
询成本。
如何确定使用多长的前缀
实际上,我们在建立索引时关注的是区分度,区分度越高越好。因为区分度越高,意味着重复的键值越少。因此,我们可以通过统计索引上有多少个不同的值来判断要使用多长的前缀。
查询语句:select count(distinct 字符串字段) as L from 表名;
分段查看前缀的值:select count(distinct left(字段名, 前k个)) as 列名 from 表名;
查询dev表中的cpuid的不同前缀的值
mysq1> select
->count(distinct left(cpuid,2as L2,
->count(distinct left(cpuid,3 as L3,
->count(distinct ieft(cpuid,4 as L4,
->count(distinct left(cpuid,6as L6,
->count(distinct left(cpuid,10) as L10,
->count(distinct left(cpuid,12))as L12
->from dev ;
+——-—-+-—--——+-—-——-+-—-———+------+-—--——+
| L2 | L3 | L4 | L6 | L10 | L2 |
+——-—-+-—--——+-—-——-+-—-———+------+-—--——+
| 750 | 1175 | 1191 | 1192 | 1195 | 1195 |
+-———-+-——--—+-——---+-———--+-—--—-+——-—--+
1 row in set (0.03sec)
从查询结果中可以看出当 L ≥ 4 L \geq 4 L≥4时所对应的值基本接近,所以若要添加cpuid字符串字段为索引时,只需要截取前4个字符即可。