我看到很多 mysql 索引的文章,都提到了,说如果某个字段的值分布范围很少(大量重复值),是不需要建立索引的.
但是我实际测试情况:
user_type_id字段有索引:
create table user_score_have_index
(
id int auto_increment
primary key,
score int default '0' not null,
user_type_id tinyint(2) default '0' not null
);
create index user_score_have_index_score_index
on user_score_have_index (score);
create index user_score_have_index_user_type_id_index
on user_score_have_index (user_type_id);
user_type_id字段无索引:
create table user_score_no_index
(
id int auto_increment
primary key,
score int default '0' not null,
user_type_id tinyint(2) default '0' not null
);
两张表数据一模一样, user_type_id 只有 1,2,3,4,5 五种值.
执行 explain 效果:
有索引:
无索引:
然后执行时间:
有索引用时 1s
无索引用时 6s
可以看到查询速度显著提高.
那么为什么还有这种说法呢?