mysql之多列索引
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查詢,使用到了多列索引。
轉載于:https://www.cnblogs.com/freephp/p/4783178.html
總結
以上是生活随笔為你收集整理的mysql之多列索引的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 教你鉴别iPhone6全球版本型号
- 下一篇: 手机内存减少五大原因?怎么清理iPhon