Memory & MyISAM 引擎小注意!

今天有朋友問題,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

id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE t1_memory ALL idx_u1 (NULL) (NULL) (NULL) 3000 Using where

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

query result

id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE t1_myisam range idx_u1 idx_u1 9 (NULL) 1 Using 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

id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE t1_memory range idx_u1 idx_u1 9 (NULL) 2 Using where

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

本文出自 「上帝,我們不見不散!」 博客,請務必保留此出處http://yueliangdao0608.blog.51cto.com/397025/228925優化

相關文章
相關標籤/搜索