26.进阶-索引-使用规则-SQL提示

26.进阶-索引-使用规则-SQL提示

(1)SQL提示

目前tb_user表的数据情况如下:

image-20240702232442015

索引情况如下:

image-20240702232501278

把上述的 idx_user_age, idx_email 这两个之前测试使用过的索引直接删除。

drop index idx_user_age on tb_user;
drop index idx_email on tb_user;

A. 执行SQL : explain select * from tb_user where profession = ‘软件工程’;

image-20240702232524541

查询走了联合索引。

B. 执行SQL,创建profession的单列索引:create index idx_user_pro on tb_user(profession);

image-20240702232545342

C. 创建单列索引后,再次执行A中的SQL语句,查看执行计划,看看到底走哪个索引。

image-20240702232559916

测试结果,我们可以看到,possible_keys中 idx_user_pro_age_sta,idx_user_pro 这两个索引都可能用到,最终MySQL选择了idx_user_pro_age_sta索引。这是MySQL自动选择的结果。

那么,我们能不能在查询的时候,自己来指定使用哪个索引呢? 答案是肯定的,此时就可以借助于MySQL的SQL提示来完成。 接下来,介绍一下SQL提示。

SQL提示,是优化数据库的一个重要手段,简单来说,就是在SQL语句中加入一些人为的提示来达到优化操作的目的。

1). use index : 建议MySQL使用哪一个索引完成此次查询(仅仅是建议,mysql内部还会再次进行评估)。
explain select * from tb_user use index(idx_user_pro) where profession = '软件工程';
2). ignore index : 忽略指定的索引。
explain select * from tb_user ignore index(idx_user_pro) where profession = '软件工程';
3). force index : 强制使用索引。
explain select * from tb_user force index(idx_user_pro) where profession = '软件工程';

示例演示:

A. use index

explain select * from tb_user use index(idx_user_pro) where profession = '软件工程';

image-20240702232731330

B. ignore index

explain select * from tb_user ignore index(idx_user_pro) where profession = '软件工程';

image-20240702232748504

C. force index

explain select * from tb_user force index(idx_user_pro_age_sta) where profession = '软件工程';

image-20240702232812435

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值