在 MySQL 数据库中,当数据表数据量达到一定量的时候我们就会为表创建索引,使用索引提高数据查询效率。但是,并不是任何时候都会触发索引查询;
在 MySQL 中,不等号 != 在主键字段和唯一索引字段中会走索引,在普通索引的字段上不会走索引。下面将逐一验证:
Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 31 Server version: 5.7.24 MySQL Community Server (GPL) Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql>
创建一张简单 user 表,且在 name 列上面创建普通索引。SQL 语句如下:
CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT NULL, `sex` varchar(255) DEFAULT NULL, `age` int(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `index_name` (`name`) USING BTREE ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
然后执行下面 SQL 语句:
explain select * from user u where u.name!='张三';
使用 explain 查看普通索引字段,没有走索引。如下图:
【小技巧】
查看某个SQL是否走索引,直接查看 explain 输出信息中的 type 列,如果 type 列不是 all,则说明表走了索引。假如我们根据 id 进行查询,SQL 如下:
explain select * from user u where u.id!=1;使用 explain 查看 SQL语句,走索引了。如下图:
创建一张简单 user 表,且在 name 列上面创建普通索引。SQL 语句如下:
CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT NULL, `sex` varchar(255) DEFAULT NULL, `age` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
然后执行下面 SQL 语句:
explain select * from user u where u.id!=1;
使用 explain 查看主键索引字段,走索引了,如下图:
创建一张简单 user 表,且在 name 列上面创建唯一索引。SQL 语句如下:
CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT NULL, `sex` varchar(255) DEFAULT NULL, `age` int(11) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `index_name` (`name`) USING BTREE ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
然后执行下面SQL语句:
explain select * from user u where u.name!='张三';
使用 explain 查看唯一索引字段,不走索引。如下图: