MySQL 查询 where 字段和值类型不一致不走索引问题排查

1. MySQL 查询 where 字段和值类型不一致不走索引问题排查

1.1. 准备

创建一张表,包含varcharcharint类型字段,每个字段加上索引。

create table `t_demo`
(
    `id`            int(11)    not null auto_increment,
    `varchar_field` varchar(1) not null,
    `char_field`    char(1)    not null,
    `int_field`     int(1)     not null,
    primary key (`id`),
    index (`varchar_field`),
    index (`char_field`),
    index (`int_field`)
);

1.2. 测试 where 字段在不同值类型情况下索引表现

1.2.1. 测试一、varchar 字段数值类型值

EXPLAIN SELECT * FROM t_demo WHERE varchar_field=1;
id select_type table partitions type possible_keys key key_len ref rows filtered Extra
1 SIMPLE t_demo null ALL varchar_field null null null 1 100 Using where

结果:不走索引。

1.2.2. 测试二、varchar 字段字符串值

EXPLAIN SELECT * FROM t_demo WHERE varchar_field='1';
id select_type table partitions type possible_keys key key_len ref rows filtered Extra
1 SIMPLE t_demo null ref varchar_field varchar_field 5 const 1 100 null

结果:走索引。

1.2.3. 测试三、char 字段数值类型值

EXPLAIN SELECT * FROM t_demo WHERE char_field=1;
id select_type table partitions type possible_keys key key_len ref rows filtered Extra
1 SIMPLE t_demo null ALL char_field null null null 1 100 Using where

结果:不走索引。

1.2.4. 测试四、char 字段字符串值

EXPLAIN SELECT * FROM t_demo WHERE char_field='1';
id select_type table partitions type possible_keys key key_len ref rows filtered Extra
1 SIMPLE t_demo null ref char_field char_field 3 const 1 100 null

结果:走索引。

1.2.5. 测试五、int 字段字符串值

EXPLAIN SELECT * FROM t_demo WHERE int_field='1';
id select_type table partitions type possible_keys key key_len ref rows filtered Extra
1 SIMPLE t_demo null ref int_field int_field 4 const 1 100 null

结果:走索引。

1.2.6. 测试六、int 字段数值类型值

EXPLAIN SELECT * FROM t_demo WHERE int_field=1;
id select_type table partitions type possible_keys key key_len ref rows filtered Extra
1 SIMPLE t_demo null ref int_field int_field 4 const 1 100 null

结果:走索引。

1.3. 总结

字段类型 值类型 是否走索引
varchar 数值
varchar 字符串
char 数值
char 字符串
int 数值
int 字符串

where 查询条件字段类型应该和值类型保持一致,否则可能不走索引。

posted @ 2024-07-09 14:42  Jason207010  阅读(174)  评论(0)    收藏  举报