zoukankan      html  css  js  c++  java
  • [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

  • 相关阅读:
    JavaScript学习笔记(六)——Map、Set与iterable
    JavaScript学习笔记(五)——条件判断与循环
    JavaScript学习笔记(四)——对象
    JavaScript学习笔记(三)——数组
    抽象代数 第三章 群
    进栈序列为(1,2,3..,n)有多少种出栈顺序
    Win10 快捷键
    主项定理Master Method
    算法导论笔记 第三十章 多项式与快速傅里叶变化
    算法导论笔记 第二十九章 线性规划
  • 原文地址:https://www.cnblogs.com/taoshihan/p/12298037.html
Copyright © 2011-2022 走看看