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 @   Jason207010  阅读(107)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示