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的運算方法,更多相關內容請關注php中文網。
相關推薦:
如何透過php 使用curl模擬ip和來源進行存取
以上是關於mysql explain中key_len的計算方法解說的詳細內容。更多資訊請關注PHP中文網其他相關文章!