[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,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

相关文章

优化MySQL数据库发布系统存储的方法有:1.mysql库主从读写分...
使用mysql的方法:在“我的电脑”→右键→“管理”→“服务”...
在mysql中查看root用户权限的方法:1.命令行启动mysql服务;...
MySQL主从复制是用来备份一个与主数据库一样环境的从数据库,...
运行mysql的方法1.启动mysql服务,在“我的电脑”→右键→“...
开启mysql的方法1.可以通过快捷键win+r,输入cmd,打开窗口,...