Mysql的key_len计算方法

说明

使用mysql的explain时,ken_len表示索引使用的字节数,根据这个值,就能够判断索引使用状况,特别是在组合索引的时候,判断全部的索引字段是否都被查询用到。html

环境

Mysql 5.6.19-logmysql

计算基础

1. 数据类型自己占字节长度sql

int(11)  4
tinyint(4)  1
timestamp  4
datetime  8

2. 索引字段的附加信息ide

定长类型:char\int\datetime等,须要有是否为空的标记,占用1个字节。若是字段定义为非空(not null)时,不占用字节。
变长类型:varchar等,须要是否为空的标记和长度信息,共占用2个字节。

3. 字符集编码

gbk编码为:1个字符2个字节
utf8编码为:1个字符3个字节
utf8mb4编码为:1个字符4个字节

示例

output:
| id | select_type | table    | type  | possible_keys   | key             | key_len | ref  | rows  | Extra                                              |
+----+-------------+----------+-------+-----------------+-----------------+---------+------+-------+----------------------------------------------------+
|  1 | SIMPLE      | tv_video | range | idx_media_audit | idx_media_audit | 167     | NULL | 18127 | Using index condition; Using where; Using filesort |

KEY `idx_media_audit` (`source_type`,`ol_status`,`op_user`,`updated_at`,`created_at`) USING BTREE

计算字节长度:
int(11)  4 [+1 not null]
tinyint(4)  1 [+1 not null]
varchar(40)  40 * 4 +2
timestamp()  4 [+1 not null]
timestamp()  4 [+1 not null]

key_len 167 = 4 + 1 + 160 + 2 = 167

结论:用索引只用到了前3个字段

相关文章:

mysql 各数据类型的 大小及长度code

mysql explain 中key_len的计算htm

浅谈MySQL中utf8和utf8mb4的区别blog

相关文章
相关标签/搜索