MsSql

关注公众号 jb51net

关闭
首页 > 数据库 > MsSql > SQL不走索引

浅谈SQL不走索引的几种常见情况

作者:Muscleheng

本文主要介绍了MySQL中SQL不走索引的常见原因,如条件未命中索引或查询类型导致全表扫描,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

我们写的SQL语句很多时候where条件用到了添加索引的列,但是却没有走索引,在网上找了资料,发现不是很准确,所以自己验证了一下,记一下笔记。

这里实验数据库为 MySQL(oracle也类似)。

查看表的索引的语句: show keys from 表名

查看SQL执行计划的语句(SQL语句前面添加 explain 关键字):explain select* from users u where u.name = 'mysql测试'

第一步、创建一个简单的表并添加几条测试数据

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  `name` varchar(255) DEFAULT NULL,
  `upTime` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `pk_users_name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;

设置索引的字段:id、name;

第二步、查看我们表的索引

# 查看索引
show keys from users

可以得到如下信息,其中id、name及为我们建的索引

第三步、通过执行计划查看我们的SQL是否使用了索引

执行如下语句得到:

explain select * from users u where u.name = 'mysql测试'

字段说明:

从这里可以看出,我们使用了索引,因为name是加了索引的;

tryp说明:

不走索引的情况,例如:

执行语句:

# like 模糊查询 前模糊或者 全模糊不走索引
explain select * from users u where u.name like '%mysql测试' 

可以看出,key 为null,没有走索引。

下面是几种测试例子:

# like 模糊查询 前模糊或者 全模糊不走索引
explain select * from users u where u.name like '%mysql测试' 

# or 条件不走索引,只要有一个条件字段没有添加索引,都不走,如果条件都添加的索引,也不一定,测试
的时候发现有时候走,有时候不走,可能数据库做了处理,具体需要先测试一下
explain select * from users u where u.name = 'mysql测试' or u.password ='JspStudy'

# or 条件都是同一个索引字段,走索引
explain  select * from users u where u.name= 'mysql测试' or u.name='333'

# 使用 union all 代替 or 这样的话有索引例的就会走索引
explain
select * from users u where u.name = 'mysql测试' 
union all
select * from users u where u.password = 'JspStudy'

# in 走索引
explain select * from users u where u.name in ('mysql测试','JspStudy')

# not in 不走索引
explain select * from users u where u.name not in ('mysql测试','JspStudy')

# is null 走索引
explain select * from users u where u.name is null 

# is not null  不走索引
explain select * from users u where u.name is not null 

# !=、<> 不走索引
explain select * from users u where u.name <> 'mysql测试'

# 隐式转换-不走索引(name 字段为 string类型,这里123为数值类型,进行了类型转换,所以不走索引,改为 '123' 则走索引)
explain select * from users u where u.name = 123

# 函数运算-不走索引
explain select *  from users u where  date_format(upTime,'%Y-%m-%d') = '2019-07-01'
# and 语句,多条件字段,最多只能用到一个索引,如果需要,可以建组合索引
explain select * from users where id='4' and username ='JspStudy' 

做SQL优化,我们最好用 explain 查看SQL执行计划,理论不一定正确,而且不同的数据库,不同的sql语句可能有不同的结果,最好是一边测试一边优化。

到此这篇关于浅谈SQL不走索引的几种常见情况的文章就介绍到这了,更多相关SQL不走索引内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文