mysql 复合索引 长度_[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,'taoshihan',2,2,0);

insert into index_test values(null,'taoshihan',2,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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值