[MySQL] mysql索引的长度计算和联合索引

1.所有的索引字段,如果没有设置not null,则需要加一个字节。
2.定长字段,int占4个字节、date占3个字节、char(n)占n个字符。
3.变长字段,varchar(n),则有n个字符+两个字节。
4.不同的字符集,一个字符占用的字节数不同。latin1编码的,一个字符占用1个字节,gbk编码的,一个字符占用2个字节,utf8编码的,一个字符占用3个字节。 utf8mb4是一个字符占4个字节
5.使用explain语句查询到的key_len字段,可以适用于上面的计算规则,可以看到查询是否使用到了联合索引
6.mysql优化器会对条件中的 and的前后顺序根据多列索引顺序自动纠正过来

通过索引的长度查看下面sql语句是否使用到了索引
CREATE TABLE `index_test` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL DEFAULT '',
`gid` int(11) NOT NULL DEFAULT '0',
`age` int(11) NOT NULL DEFAULT '0',
`score` int(10) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `name_gid_age_index` (`name`,`gid`,`age`),
KEY `score_index` (`score`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8
insert into index_test values(null,'taoshihan',2,1,0);
insert into index_test values(null,'taoshihan',2,2,0);
insert into index_test values(null,'taoshihan',2,3,0);

explain select * from index_test where name='taoshihan' group by gid;
+----+-------------+------------+------------+-------+--------------------+--------------------+---------+------+------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+------------+------------+-------+--------------------+--------------------+---------+------+------+----------+-------------+
| 1 | SIMPLE | index_test | NULL | index | name_gid_age_index | name_gid_age_index | 310 | NULL | 6 | 66.67 | Using where |
+----+-------------+------------+------------+-------+--------------------+--------------------+---------+------+------+----------+-------------+

key_len的长度是310,也就是100*3+2 + 4 +4

posted @ 2020-02-12 10:27  唯一客服系统开发笔记  阅读(1505)  评论(0编辑  收藏  举报