MySQL 的索引

来源:互联网 发布:mac pusher 编辑:程序博客网 时间:2024/04/27 22:06

第一个索引结构

有如下表结构

CREATE TABLE `tb` (  `a` int(11) DEFAULT NULL,  `b` int(11) DEFAULT NULL,  `c` int(11) DEFAULT NULL,  KEY `abc` (`a`,`b`,`c`)) ENGINE=InnoDB DEFAULT CHARSET=utf8
具体查看是否使用到索引用mysql> explain select * from tb where a = 'xx' and c = 'xx'\G*************************** 1. row ***************************           id: 1  select_type: SIMPLE        table: tb         type: refpossible_keys: abc          key: abc      key_len: 5          ref: const         rows: 1        Extra: Using where; Using index1 row in set (0.00 sec)
where a=xx and b=xx and c=xxx 此语句可以用到索引 where b=xx and a=xx and c=xxx 同上,顺序没有关系,同样能用到索引,mysql内部会做优化where a=xx and b=xx 可以用到索引where a=xx and c=xx 可以用到索引where b=xx and c=xx 用不到索引 where b=xx 用不到索引 where c=xx 用不到索引Where a=xx order by b 可以用到索引Where a>xx order by c 可以用到索引联合索引中有一个规则:左前缀匹配规则a b c 之间的联系断了,就会影响索引的效率where a=xx and c=xx 这个例子中索引的层面只是到了a层面上where b=xx and c=xx 这个例子中索引不是从a开始,所以用不到索引

第二个索引结构

CREATE TABLE `tb` (  `a` int(11) DEFAULT NULL,  `b` int(11) DEFAULT NULL,  `c` int(11) DEFAULT NULL,  KEY `a` (`a`),  KEY `b` (`b`),  KEY `c` (`c`)) ENGINE=InnoDB DEFAULT CHARSET=utf8
Where a=1 order by c 用到了索引a

第三个索引结构

CREATE TABLE `tb` (  `a` int(11) DEFAULT NULL,  `b` int(11) DEFAULT NULL,  `c` int(11) DEFAULT NULL,  `d` int(11) DEFAULT NULL,  KEY `ab` (`a`,`b`),  KEY `acd` (`a`,`c`,`d`)) ENGINE=InnoDB DEFAULT CHARSET=utf8
Where a=xx and c!=xx and d=xx order by b  用到索引abWhere a=xx and c=xx and d!=xx order by b  用到索引ab

Explain 参数详解

Type: 类型,是否使用了索引还是全表扫描
Possible_key: 可能选择的索引
Key: 实际使用上的索引是哪个字段
Ken_len: 真正使用了哪些索引,不为 NULL 的就是真实使用的索引
Ref: 显示了哪些字段或者常量被用来和 key 配合从表中查询记录出来
Rows: 显示了MySQL认为在查询中应该检索的记录数
Extra: 显示了查询中MySQL的附加信息,关心Using filesort 和 Using temporary,性能杀手

0 0
原创粉丝点击