【MySQL】索引 —— 使用规则 —— SQL提示

一、引入

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

image-20240718172932656

索引情况如下:

image-20240718173324296

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

image-20240718173351848

查询走了联合索引。


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

image-20240718173428021

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

image-20240718173446735

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

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

B. ignore index

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

image-20240718173810508

C. force index

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

image-20240718173835099

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值