如何计算key_len=?
列的key_len长度,按照每列的最大预留长度(最大储值长度)来做的计算。单表越少越好,联合表越多越好。
影响最大存储预留长度(字节)因素:


话不多说了,我们直接上例子。表结构如下。^_^
create table test (id int not null primary key auto_increment,a int not null , #4b char(10) not null , #4*10 40c char(5) , #5*4+1 21d varchar(20) not null , #20*4+2 82e varchar(10) #10*4+2+11 43)engine=innodb charset=utf8mb4;
如果a,b,c,d,e的联合索引,全部覆盖到,key_len是多少
select 4+40+21+82+43;

select 4+40+21+82;

select 4+40+21;
select 4+40;
联合索引应用细节
举个栗子:create table test (id int not null primary key auto_increment,a int not null , # 4b int , # 5c char(10) not null , # 40d varchar(10), # 43e varchar(10) not null # 42)engine=innodb charset=utf8mb4;


联合索引不同覆盖场景
举个栗子:CREATE TABLE `t100w` (`id` int(11) DEFAULT NULL,`num` int(11) DEFAULT NULL, # 5`k1` char(2) DEFAULT NULL, # 9`k2` char(4) DEFAULT NULL, # 17`dt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4

全覆盖
情景1:走联合索引
desc select * from t100w where num=913759 and k1="ej" and k2="EFfg";
情景2:条件顺序无所谓
desc select * from t100w where k1="ej" and k2="EFfg" and num=913759;

情景3:in查询走联合索引
desc select * from t100w where k1="ej" and k2 in ("EFfg","abc") and num=913759;
情景4:最后一个非等于走联合索引
desc select * from t100w where num=913759 and k1="ej" and k2 like "EF%";
desc select * from t100w where num=913759 and k1="ej" and k2 > "EFfg";
desc select * from t100w where num=913759 and k1 > "zz" and k2 like "EF%";

desc select * from t100w where num=913759 and k1="ej";desc select * from t100w where num=913759 and k2 like "EF%";desc select * from t100w where num=913759 and k1 != "zz" and k2 like "EFfg";





