mysql什么情况下sql语句用不到索引

本文介绍了MySQL中索引未被利用的一些情况,包括OR条件中部分字段无索引、不遵循最左前缀原则、LIKE查询以%开头、数据类型隐形转换、索引列进行数学运算、使用函数以及MySQL选择全表扫描等。了解这些情况有助于优化查询性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1:条件中有or,并且所有条件字段都建了索引,才能用到索引,否则用不到。

explain select * from sdb_b2c_members where mobile='18202139749' or name = '邢进'

这条sql语句中的mobile和name都建了索引,所以用到了索引。
在这里插入图片描述

explain select * from sdb_b2c_members where mobile='18202139749' or point = '3034'

这条sql语句中的mobile字段有索引,但是point字段没索引,所以没用到索引。
在这里插入图片描述
所以:要想使用or,又想让索引生效,只能将or条件中的每个列都加上索引

2:对于多列索引,要遵循最左前缀原则,否则用不到索引(除非这个字段在多列索引之外又建立了单个索引)。
比如,我建了一个组合索引,索引顺序是:a b c d
where a = ‘’;//能用到索引
where a = ‘’ and b = ‘’ and c = ‘’ and d = ‘’;//能用到索引
where a = ‘’ and b=’’ and d = ‘’ //此时d用不到索引
where a = ‘’ and b > 10 //a能用到索引,b用不到
where b = ‘’ //用不到索引

建表:
CREATE TABLE student3(
    id INT(11)  auto_increment,
    name VARCHAR(10) not null,
    age int(10) not null default 0,
    height int(10) not null default 0,
    weight int(10) not null default 0,
    primary key (id),
    key n_a_h_w(name,age,height,weight)
  )ENGINE=INNODB;

跳过联合索引的第一个字段name,直接用第二个字段:发现type列是index,表示进行了全索引扫描。
explain select * from student3 where age = 20;
+----+-------------+----------+------------+-------+------
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值