您的位置:首页 > 数据库 > MySQL

mysql之多列索引

2015-09-05 14:18 701 查看
mysql的多列索引是经常会遇到的问题,怎样才能有效命中索引,是本文要探讨的重点。

多列索引使用的Btree,也就是平衡二叉树。简单来说就是排好序的快速索引方式。它的原则就是要遵循左前缀索引。

多个索引从左边往右都使用上,才能使用到整个多列索引。

下面我先建立一个简单的表做实验:

create table t6 (

c1 char(1) not null default '',

c2 char(1) not null default '',

c3 char(1) not null default '',

c4 char(1) not null default '',

c5 char(1) not null default '',

key(c1,c2,c3,c4,c5)

) engine myisam charset utf8;

再分别insert into一些数据。

分别做以下一些查询:

1.

explain select * from t6 where c1='a' and c2='b' and c4>'a' and c3="c" \G;
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: t6
type: range
possible_keys: c1
key: c1
key_len: 12
ref: NULL
rows: 2
Extra: Using where
1 row in set (0.00 sec)

这里使用到了c1,c2,c3,c4索引,特别c4是一个范围查询,所以type为range,依次c1,c2,c3被命中索引。

2.

explain select * from t6 where c1='a' and c4='a' order by c3,c2 \G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: t6
type: ref
possible_keys: c1
key: c1
key_len: 3
ref: const
rows: 2
Extra: Using where; Using filesort
1 row in set (0.00 sec)

过程中先命中了c1,然后在order by c3,c2的时候由于先去use c3做排序,从而联合索引断了。using filesort表明没有使用到多列合索引,而是做了文件内排序。

3.

explain select * from t6 where c1='a' and c4='a' order by c2,c3 \G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: t6
type: ref
possible_keys: c1
key: c1
key_len: 3
ref: const
rows: 2
Extra: Using where
1 row in set (0.00 sec)

反之命中c1索引后,先用c2排序,再是c3来排序,分别命中,最后是c4='a'做where查询,使用到了多列索引。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: