mysql> create table SUser(
ID bigint unsigned primary key,
email varchar(64),
...
)engine=innodb;
这里会进行全表扫描
mysql> select f1, f2 from SUser where email='xxx';
这里给邮箱加索引
mysql> alter table SUser add index index1(email);
或 这里的长度是取前六个字节
mysql> alter table SUser add index index2(email(6));
上面的俩种索引的区别:前缀索引占的空间少
缺点是性能下降
select id,name,email from SUser where email='[email protected]';
索引一只回表一次,索引二会回表多次
如果定义好前缀索引的长度也可以使扫描的行数减少。
那有什么方法确定合适的长度呢?
mysql> select count(distinct email) as L from SUser;
mysql> select
count(distinct left(email,4))as L4,
count(distinct left(email,5))as L5,
count(distinct left(email,6))as L6,
count(distinct left(email,7))as L7,
from SUser;
前缀索引对覆盖索引的影响:
select id,email from SUser where email='[email protected]';
select id,name,email from SUser where email='[email protected]';
前缀索引不会使用覆盖索引。
如果前缀索引的区分度不好的时候,解决办法。
一:使用倒序存储:
mysql> select field_list from t where id_card = reverse('input_id_card_string');
二:使用hash 字段:增加一个字段,给email做hash,
mysql> alter table t add id_card_crc int unsigned, add index(id_card_crc);
mysql> select field_list from t where id_card_crc=crc32('input_id_card_string') and id_card='input_id_card_string'
id_card_crc有可能相同,如果相同就判断id_card.这里也用到了索引。