mysql的explain敕令能够剖析sql的机能,其中有一项是key_len(索引的长度)的统计。本文将剖析mysql explain中key_len的计算要领。
1.建立测试表及数据
CREATE TABLE `member` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(20) DEFAULT NULL, `age` tinyint(3) unsigned DEFAULT NULL, PRIMARY KEY (`id`), KEY `name` (`name`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;INSERT INTO `member` (`id`, `name`, `age`) VALUES (NULL, 'fdipzone', '18'), (NULL, 'jim', '19'), (NULL, 'tom', '19');
2.检察explain
name的字段范例是varchar(20),字符编码是utf8,一个字符占用3个字节,那末key_len应该是 20*3=60。
mysql> explain select * from `member` where name='fdipzone'; +----+-------------+--------+------+---------------+------+---------+-------+------+-----------------------+| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+--------+------+---------------+------+---------+-------+------+-----------------------+| 1 | SIMPLE | member | ref | name | name | 63 | const | 1 | Using index condition | +----+-------------+--------+------+---------------+------+---------+-------+------+-----------------------+
explain的key_len为63,多出了3。
name字段是许可NULL,把name改成NOT NULL再测试
ALTER TABLE `member` CHANGE `name` `name` VARCHAR(20) NOT NULL;mysql> explain select * from `member` where name='fdipzone'; +----+-------------+--------+------+---------------+------+---------+-------+------+-----------------------+| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+--------+------+---------------+------+---------+-------+------+-----------------------+| 1 | SIMPLE | member | ref | name | name | 62 | const | 1 | Using index condition | +----+-------------+--------+------+---------------+------+---------+-------+------+-----------------------+
如今key_len为62,比适才少了1,但照样多了2。能够肯定,字段为NULL会多占用一个字节。
name字段范例为varchar,属于变长字段,把varchar改成char再测试
ALTER TABLE `member` CHANGE `name` `name` CHAR(20) NOT NULL;mysql> explain select * from `member` where name='fdipzone'; +----+-------------+--------+------+---------------+------+---------+-------+------+-----------------------+| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+--------+------+---------------+------+---------+-------+------+-----------------------+| 1 | SIMPLE | member | ref | name | name | 60 | const | 1 | Using index condition | +----+-------------+--------+------+---------------+------+---------+-------+------+-----------------------+
改成定长字段后,key_len为60,与展望的一致。
总结:运用变长字段须要分外增添2个字节,运用NULL须要分外增添1个字节,因而对因而索引的字段,最好运用定长和NOT NULL定义,进步机能。
本篇文章解说了mysql explain中key_len的计算要领,更多相干内容请关注ki4网。
相干引荐:
怎样经由过程php 运用curl模仿ip和泉源举行接见
经由过程mysql 转换NULL数据要领
关于php 函数运用可变数目的参数的相干内容
以上就是关于mysql explain中key_len的计算要领解说的细致内容,更多请关注ki4网别的相干文章!