索引失效的几种情况

常见的有如下几种情况

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL COMMENT '名字',
  `sex` tinyint(5) DEFAULT '0' COMMENT '性别',
  `address` varchar(255) DEFAULT NULL COMMENT '住址',
  `card_id` varchar(18) DEFAULT NULL COMMENT '身份证',
  `age` int(3) DEFAULT NULL COMMENT '年龄',
  PRIMARY KEY (`id`),
  KEY `name` (`name`),
  KEY `card_id` (`card_id`) USING BTREE,
  KEY `age` (`age`) USING BTREE,
  KEY `name_and_address` (`name`,`address`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

1 对于使用 like 查询, 查询如果是 ‘%aaa’ 不会使用索引,而 ‘aaa%’ 会使用到索引。

explain
select * from user where name like "%meiyu"
explain
select * from user where name like "meiyu%"

在这里插入图片描述
在这里插入图片描述
2 对于索引字段如果发生类型自动转化也会失效

--card_id 为varchar类型
explain
select * from user where card_id ='421127199604124781'  --索引有效
select * from user where card_id =421127199604124781 --索引失效

注意:字符串类型要加引号

3. 如果条件中有 or, 有条件没有使用索引,即使其中有条件带索引也不会使用。

--card_id 有索引 address没有索引
explain
select * from user where card_id ='421127199604124781'  or address = '深圳龙岗'

4对列进行计算或者是使用函数,则该列的索引会失效

explain
select * from user where age+10 = 18

5联合索引遵循最左匹配原则

KEY `name_and_address` (`name`,`address`) USING BTREE

--有效
explain
select * from user where name = 'huangyaoshi' and address = '桃花岛'
--有效
explain
select * from user where name = 'huangyaoshi' 
--无效
explain
select * from user where address = '桃花岛'

注意 就是最左侧name字段必须要有

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值