key_len的含義
在MySQL中,可以通過explain查看SQL語句所走的路徑,如下所示:
| mysql> create table t(a int primary key, b int not null, c int not null, index(b)); Query OK, 0 rows affected (0.01 sec) mysql> explain select b from t ; +----+-------------+-------+-------+---------------+------+---------+------+------+-------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+-------+---------------+------+---------+------+------+-------------+ | 1 | SIMPLE | t | index | NULL | b | 4 | NULL | 1 | Using index | +----+-------------+-------+-------+---------------+------+---------+------+------+-------------+ 1 row in set (0.00 sec) | 
其中,key_len表示使用的索引長度,是以字節(jié)為單位。在上面的例子中,由于int型占用4個(gè)字節(jié),而索引中只包含了1列,所以,key_len是4。
下面是聯(lián)合索引的情況:
| mysql> alter table t add index ix(b, c);Query OK, 0 rows affected (0.03 sec)Records: 0 Duplicates: 0 Warnings: 0mysql> explain select b, c from t ;+----+-------------+-------+-------+---------------+------+---------+------+------+-------------+| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |+----+-------------+-------+-------+---------------+------+---------+------+------+-------------+| 1 | SIMPLE | t | index | NULL | ix | 8 | NULL | 1 | Using index |+----+-------------+-------+-------+---------------+------+---------+------+------+-------------+1 row in set (0.00 sec) | 
聯(lián)合索引ix包含了2列,并且都使用到了,所以,這里ken_len是8。
到這里,我們已經(jīng)可以理解key_len的含義了,似乎已經(jīng)沒有什么可講的了,但是,MySQL中key_len的計(jì)算還有很多需要注意的地方。
例如,我們將b這一列的NOT NULL約束去掉,然后ken_len就和我們預(yù)期不一樣了,如下所示:
| mysql> alter table t modify b int;Query OK, 0 rows affected (0.01 sec)Records: 0 Duplicates: 0 Warnings: 0 mysql> explain select b from t;+----+-------------+-------+-------+---------------+------+---------+------+------+-------------+| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |+----+-------------+-------+-------+---------------+------+---------+------+------+-------------+| 1 | SIMPLE | t | index | NULL | b | 5 | NULL | 1 | Using index |+----+-------------+-------+-------+---------------+------+---------+------+------+-------------+1 row in set (0.00 sec) | 
MySQL中key_len計(jì)算規(guī)則
MySQL中,key_len的計(jì)算規(guī)則如下:
如果列可以為空,則在數(shù)據(jù)類型占用字節(jié)的基礎(chǔ)上加1,如int型,不能為空key_len為4,可以為空key_len為5 如果列是變長的,則在數(shù)據(jù)列所占字節(jié)的基數(shù)上再加2,如varbinary(10),不能為空,則key_len為10 + 2 ,可以為空則key_len為10+2+1 如果是字符型,則還需要考慮字符集,如某列的定義是varchar(10),且是utf8,不能為空,則key_len為10 * 3 + 2,可以為空則key_len為10*3+2+1 此外,decimal列的計(jì)算方法與上面一樣,如果可以為空,則在數(shù)據(jù)類型占用字節(jié)的基礎(chǔ)上加1,但是,decimal本身所占用字節(jié)數(shù),計(jì)算就比較復(fù)雜。新聞熱點(diǎn)
疑難解答
圖片精選