一、引入
目前tb_user表的数据情况如下:
索引情况如下:
A. 执行SQL : explain select * from tb_user where profession = ‘软件工程’;
查询走了联合索引。
B. 执行SQL,创建profession的单列索引:create index idx_user_pro on tb_user(profession);
C. 创建单列索引后,再次执行A中的SQL语句,查看执行计划,看看到底走哪个索引。
测试结果,我们可以看到,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 = '软件工程';
B. ignore index
explain select * from tb_user ignore index(idx_user_pro) where profession = '软件工程';
C. force index
explain select * from tb_user force index(idx_user_pro_age_sta) where profession = '软件工程';