mysql联合索引


验证一下mysql的联合索引在什么情况下会生效,什么情况下会失效


创建一个记录表(记录条数:29306)


```CREATE TABLE `it_order_cart_20210401` (
	  `id` int(11) NOT NULL AUTO_INCREMENT,
	  `integral_id` int(11) DEFAULT NULL COMMENT '人员id',
	  `skuId` bigint(20) DEFAULT NULL,
	  `total` int(11) DEFAULT NULL COMMENT '数量',
	  `selected` int(11) DEFAULT NULL COMMENT '是否选中:0未选中 1选中',
	  `create_user` varchar(50) DEFAULT NULL COMMENT '创建人',
	  `update_user` varchar(50) DEFAULT NULL COMMENT '修改人',
	  `create_time` datetime DEFAULT NULL COMMENT '创建时间',
	  `update_time` datetime DEFAULT NULL COMMENT '修改时间'
	  PRIMARY KEY (`id`),
	  KEY `index_iss` (`integral_id`,`skuId`,`selected`) USING BTREE
	) ENGINE=InnoDB AUTO_INCREMENT=289273 DEFAULT CHARSET=utf8 COMMENT='购物车';

我们为integral_id, skuId, selected三个字段创建了联合索引
使用explain来验证一下索引的生效情况

1、当查询条件是integral_id,skuId,selected的时候

explain 
select * from it_order_cart_20210401 where integral_id = 16618 and skuId = 16618 and selected = 16618;

联合索引是生效的

2、当查询条件是integral_id的时候

explain 
select * from it_order_cart_20210401 where integral_id = 16618;

联合索引是生效的

3、当查询条件是skuId的时候

explain
select * from it_order_cart_20210401 where skuId = 16618;

联合索引失效了

4、当查询条件是selected

explain 
select * from it_order_cart_20210401 where selected = 16618;

联合索引失效了

5、当查询条件是integral_id 和 skuId 的时候

explain 
select * from it_order_cart_20210401 where integral_id = 16618 and skuId = 16618;

发现条件是第一第二位,但是索引依然生效了

6、当查询条件是integral_id 或 skuId 的时候

explain 
select * from it_order_cart_20210401 where integral_id = 16618 or skuId = 16618;

联合索引是失效了(or不支持)

7、当联合索引是skuId 和 integral_id 的时候

explain 
select * from it_order_cart_20210401 where skuId = 16618 and integral_id = 16618;

发现顺序虽然变了,但是索引依然生效

8、当联合索引是 integral_id 和 selected 的时候

explain 
select * from it_order_cart_20210401 where integral_id = 16618 and selected = 16618;

发现虽然条件是第一第三位,但是索引依然生效了

9、当联合索引是 skuId和 selected 的时候

explain 
select * from it_order_cart_20210401 where skuId = 16618 and selected = 16618;

发现条件是第二第三位,索引失效了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值