(1).索引字段的附加信息:能够分为变长和定长数据类型讨论,当索引字段为定长数据类型,好比char,int,datetime,须要有是否为空的标记,这个标记须要占用1个字节;对于变长数据类型,好比:varchar,除了是否为空的标记外,还须要有长度信息,须要占用2个字节;sql
(备注:当字段定义为非空的时候,是否为空的标记将不占用字节)测试
(2).同时还须要考虑表所使用的字符集,不一样的字符集,gbk编码的为一个字符2个字节,utf8编码的一个字符3个字节;编码
先看定长数据类型的一个例子(编码为gbk):blog
root@test 07:32:39>create table test_char(id int not null ,name_1 char(20),name_2 char(20), -> primary key(id),key ind_name(name_1,name_2))engine=innodb charset=gbk; root@test 07:33:55>insert into test_char values(1,’xuancan’,'taobaodba’); root@test 07:34:55>explain select * from test_char where name_1=’xuancan’\G; *************************** 1. row *************************** id: 1 select_type: SIMPLE table: test_char type: ref possible_keys: ind_name key: ind_name key_len: 41 ref: const rows: 1 Extra: Using where; Using index key_len=41=20*2+1(备注:因为name_1为空,isnull的标记被打上,须要计算1个字节) root@test 07:35:31>explain select * from test_char where name_1=’xuancan’ and name_2=’taobaodba’\G; *************************** 1. row *************************** id: 1 select_type: SIMPLE table: test_char type: ref possible_keys: ind_name key: ind_name key_len: 82 ref: const,const rows: 1 Extra: Using where; Using index key_len=82=20*2+20*2+1+1(备注:因为name_1,name_2两列被使用到,但两列都为为空,须要计算2个字节)
变长数据类型(gbk编码):索引
root@test 08:30:51>create table test_varchar(id int not null ,name_1 varchar(20),name_2 varchar(20), -> primary key(id),key ind_name(name_1,name_2))engine=innodb charset=gbk; root@test 08:37:51>insert into test_varchar values(1,’xuancan’,'taobaodba’); root@test 08:38:14>explain select * from test_varchar where name_1=’xuancan’\G; *************************** 1. row *************************** id: 1 select_type: SIMPLE table: test_varchar type: ref possible_keys: ind_name key: ind_name key_len: 43 ref: const rows: 1 Extra: Using where; Using index key_len=43=20*2+1+2(备注:因为为name_1字段定义为空,因此须要计算1,;同时因为是变长字段varchar,因此须要加上2) root@test 08:38:46>alter table test_varchar modify column name_1 varchar(20) not null; Query OK, 1 row affected (0.52 sec) Records: 1 Duplicates: 0 Warnings: 0 root@test 08:42:11>explain select * from test_varchar where name_1=’xuancan’\G; *************************** 1. row *************************** id: 1 select_type: SIMPLE table: test_varchar type: ref possible_keys: ind_name key: ind_name key_len: 42 ref: const rows: 1 Extra: Using where; Using index key_len=42=20*2+2(备注因为name_1字段修改成not null以后,isnull的标记锁占用的字节释放掉,可是变长字段长度所占用的2个字节没有释放); 上面是测试gbk编码的测试,同时也能够测试一下其余编码的key_len计算。