Memory & MyISAM 引擎小注意!

本文探讨了MySQL中MEMORY引擎与MYISAM引擎在查询性能上的差异,通过改变MEMORY引擎的索引类型从HASH到BTREE,显著提升了范围查询的速度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天有朋友问题,MEMORY 引擎的表查询速度竟然比MYISAM引擎慢!
熟读手册后,你就不用有这样的疑问了。

我们来小解决下。
示例表结构:
create table t1_memory (
id int unsigned not null auto_increment primary key,
a1 decimal(15,12),
a2 decimal(15,12),
remark varchar(200) not null,
key idx_u1 (a1,a2)
) engine memory;

create table t1_myisam (
id int unsigned not null auto_increment primary key,
a1 decimal(15,12),
a2 decimal(15,12),
remark varchar(200) not null,
key idx_u1 (a1,a2)
) engine myisam;
示例SQL语句:
select * from t1_memory where a1>110 and a1<111 and a2>23 and a2<24;
select * from t1_myisam where a1>110 and a1<111 and a2>23 and a2<24;

语句执行计划:
explain
select * from t1_memory where a1>110 and a1<111 and a2>23 and a2<24;

query result

idselect_typetabletypepossible_keyskeykey_lenrefrowsExtra
1SIMPLEt1_memoryALLidx_u1(NULL)(NULL)(NULL)3000Using where

explain
select * from t1_myisam where a1>110 and a1<111 and a2>23 and a2<24;

query result

idselect_typetabletypepossible_keyskeykey_lenrefrowsExtra
1SIMPLEt1_myisamrangeidx_u1idx_u19(NULL)1Using where

根本原因就是默认MEMORY 引擎采用HASH索引, 所以对于RANGE INDEX 来说,我们要修改成BTREE索引。
解决办法:
变化索引类型
alter table t1_memory drop key idx_u1, add key idx_u1 using btree (a1,a2);

优化后执行计划:
explain
select * from t1_memory where a1>110 and a1<111 and a2>23 and a2<24;

query result

idselect_typetabletypepossible_keyskeykey_lenrefrowsExtra
1SIMPLEt1_memoryrangeidx_u1idx_u19(NULL)2Using where

看到了吧,咱也用上了索引。哈哈。

本文出自 “上帝,咱们不见不散!” 博客,请务必保留此出处http://yueliangdao0608.blog.51cto.com/397025/228925

转载于:https://my.oschina.net/u/585111/blog/219507

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值