记一次需强制指定使用某一索引的例子

当存在多个索引的情况下, 有时候Mysql自动选的索引并不是最优的, 此时需要显式指定一个更优索引。

如想查询今天领取且已过期状态的优惠券

刚开始使用的sql是

select * from coupon_user  where  status = '20' and create_time > current_date order by id desc ;

要等半天才有结果 查看表结构 发现status和create_time均加了索引

KEY `idx_status` (`status`),
KEY `create_time` (`create_time`),

但实际使用的是status索引 故需查询1349万多数据

idselect_typetabletypepossible_keyskeykey_lenrefrowsExtra
1SIMPLEcoupon_userangeidx_status,create_timeidx_status9const13498998Using where;

针对这种情形 可以强制使用create_time索引 此时只需查询7410条记录

select * from coupon_user force index(create_time) where  status = '20' and create_time > current_date order by id desc;
idselect_typetabletypepossible_keyskeykey_lenrefrowsExtra
1SIMPLEcoupon_userangeidx_status,create_timecreate_time47410Using index condition; Using where; Using filesort
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值