验证一下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;
发现条件是第二第三位,索引失效了