insert into music values('BITE'),('There for you'),('Scarborough Fair'),('Shape of You'),('Marvin Gaye'),('Pretty Girl'),('Pretty Boy'),('Walk Away'),('YOUTH'),('Paris');
insert into music values ('Scarborough Fair'),('Shape of You'),('Marvin Gaye'),('Pretty Girl'),('Pretty Boy'),('Walk Away'),('YOUTH'),('Paris');
select count(distinct left(name,1))/count(*) as sel1, count(distinct left(name,2))/count(*) as sel2, count(distinct left(name,3))/count(*) as sel3, count(distinct left(name,4))/count(*) as sel4 from music; +--------+--------+--------+--------+ | sel1 | sel2 | sel3 | sel4 | +--------+--------+--------+--------+ | 0.3889 | 0.5000 | 0.5000 | 0.5000 | +--------+--------+--------+--------+
4)、可以看到当前缀长度为2是已经接近完整列索引选择性,添加前缀索引
1 2 3 4 5 6 7 8 9 10
alter table music add index music_index(name(2)); Query OK, 0 rows affected (0.06 sec) Records: 0 Duplicates: 0 Warnings: 0
show index from music; +-------+------------+-------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+ | Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | +-------+------------+-------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+ | music | 1 | music_index | 1 | name | A | 9 | 2 | NULL | YES | BTREE | | | +-------+------------+-------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
5)、查询索引是否被正常应用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
select * from music where name like 's%'; +------------------+ | name | +------------------+ | Scarborough Fair | | Scarborough Fair | | Shape of You | | Shape of You | +------------------+ 4 rows in set (0.07 sec)
explain select * from music where name like 's%'; +----+-------------+-------+------------+-------+---------------+-------------+---------+------+------+----------+-------------+ | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra | +----+-------------+-------+------------+-------+---------------+-------------+---------+------+------+----------+-------------+ | 1 | SIMPLE | music | NULL | range | music_index | music_index | 11 | NULL | 4 | 100.00 | Using where | +----+-------------+-------+------------+-------+---------------+-------------+---------+------+------+----------+-------------+ 1 row in set, 1 warning (0.00 sec)