MySQL 联合索引使用情况

时间:2022-02-19 05:14:48

验证联合索引使用的情况

索引是一个排序的结构,用于快速检索和加速排序

MySQL表结构

index_test | CREATE TABLE `index_test` (
`c1` char(10) NOT NULL,
`c2` char(10) NOT NULL,
`c3` char(10) NOT NULL,
`c4` char(10) NOT NULL,
`c5` char(10) NOT NULL,
KEY `index_c1c2c3c4` (`c1`,`c2`,`c3`,`c4`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8

(1).

mysql> explain select * from index_test where c1=‘c1‘ and c2=‘c2‘ and c4>‘c4‘ and c3=‘c3‘G;
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: index_test
type: range
possible_keys: index_c1c2c3c4
key: index_c1c2c3c4
key_len: 120
ref: NULL
rows: 1
Extra: Using index condition

由key_len: 120可知,四个索引都用到了(utf8,一个字符占用3个字节);

(2).

explain select * from index_test where c1=‘c1‘ and c2=‘c2‘ and c4=‘c4‘ order by c3G;
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: index_test
type: ref
possible_keys: index_c1c2c3c4
key: index_c1c2c3c4
key_len: 60
ref: const,const
rows: 1
Extra: Using index condition; Using where

c1,c2,c3都用到了,c1,c2索引用于排序,c3索引用于排序

(3)

select * from index_test where c1=‘c1‘ and c2=‘c2‘ order by c3,c2G;
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: index_test
type: ref
possible_keys: index_c1c2c3c4
key: index_c1c2c3c4
key_len: 60
ref: const,const
rows: 1
Extra: Using index condition; Using where

c1,c2,c3 c3用到索引是因为c2是常量

(4)

explain select * from index_test where c1=‘c1‘ and c5=‘c5‘ order by c2,c3G;
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: index_test
type: ref
possible_keys: index_c1c2c3c4
key: index_c1c2c3c4
key_len: 30
ref: const
rows: 1
Extra: Using index condition; Using where

c1,c2,c3用到索引了

(5)

explain select * from index_test where c1=‘c1‘ and c2=‘c2‘ and c5=‘c5‘ order by c3,c2G;
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: index_test
type: ref
possible_keys: index_c1c2c3c4
key: index_c1c2c3c4
key_len: 60
ref: const,const
rows: 1
Extra: Using index condition; Using where

c1,c2,c3使用了索引