在一张表里有多个索引,我们where字段里条件有多个索引的值,那么究竟使用的哪个呢?
我们可以使用explain来查看,其中的key_len字段可以看得出来
比如下面这条sql
explain select * from ent_calendar_diary where email='xxxx' and diary_ID=1784;
+----+-------------+--------------------+------------+-------+-------------------------+---------+---------+-------+------+----------+-------+| ID | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |+----+-------------+--------------------+------------+-------+-------------------------+---------+---------+-------+------+----------+-------+| 1 | SIMPLE | ent_calendar_diary | NulL | const | PRIMARY,IDx_email_stime | PRIMARY | 4 | const | 1 | 100.00 | NulL |+----+-------------+--------------------+------------+-------+-------------------------+---------+---------+-------+------+----------+-------+
possible_keys里面有两个索引字段,但是看key_len 是4个字节
列类型 | key_len | 备注 |
---|---|---|
ID int | key_len = 4+1 = 5 | 允许NulL,加1-byte |
ID int not null | key_len = 4 | 不允许NulL |
user char(30) utf8 | key_len = 30*3+1 | 允许NulL |
user varchar(30) not null utf8 | key_len = 30*3+2 | 动态列类型,加2-bytes |
user varchar(30) utf8 | key_len = 30*3+2+1 | 动态列类型,加2-bytes;允许NulL,再加1-byte |
detail text(10) utf8 | key_len = 30*3+2+1 | TEXT列截取部分,被视为动态列类型,加2-bytes;且允许NulL |
备注,key_len 只指示了WHERE中用于条件过滤时被选中的索引列,是不包含 ORDER BY/GROUP BY
int类型并且not null 是4个字节,因此上面的sql是使用的主键索引
explain select * from ent_calendar_diary where email='xxxx';
+----+-------------+--------------------+------------+------+-----------------+-----------------+---------+-------+------+----------+-------+| ID | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |+----+-------------+--------------------+------------+------+-----------------+-----------------+---------+-------+------+----------+-------+| 1 | SIMPLE | ent_calendar_diary | NulL | ref | IDx_email_stime | IDx_email_stime | 767 | const | 111 | 100.00 | NulL |+----+-------------+--------------------+------------+------+-----------------+-----------------+---------+-------+------+----------+-------+
这个是767个字节,varchar(255) not null 255 * 3 +2正好符合,因此是使用的email那个普通索引
CREATE table `ent_calendar_diary` (
`diary_ID` int(10) unsigned NOT NulL auto_INCREMENT,
`email` varchar(255) NOT NulL,
`Title` varchar(100) NOT NulL,
`summary` varchar(500) NOT NulL DEFAulT '',
`stime` bigint(11) NOT NulL DEFAulT '0',
`ctime` int(10) unsigned NOT NulL DEFAulT '0',
PRIMARY KEY (`diary_ID`),
KEY `IDx_email_stime` (`email`,`stime`)
) ENGINE=InnoDB auto_INCREMENT=1809 DEFAulT CHARSET=utf8
以上是内存溢出为你收集整理的[MySQL] 查看explain中的key_len判断究竟使用了哪个索引全部内容,希望文章能够帮你解决[MySQL] 查看explain中的key_len判断究竟使用了哪个索引所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)