表格的建立:
表格当前有的索引:
show index from tb_user;
执行SQL:
explain select * from tb_user where profession = '软件工程';
查询走了联合索引
执行SQL,创建profession的单列索引:
create index idx_user_pro on tb_user(profession); show index from tb_user;
创建单列索引后,再次执行:
explain select * from tb_user where profession = '软件工程';
possible_keys中 idx_user_pro_age_sta,idx_user_pro 这两个索引都可能用到,最终MySQL选择了idx_user_pro_age_sta索引。
这是MySQL自动选择的结果。
我们可以借助于MySQL的SQL提示来指定使用哪个索引。
SQL提示,是优化数据库的一个重要手段,简单来说,就是在SQL语句中加入一些人为的提示指定使用哪个索引来达到优化操作的目的。
use index
:
建议MySQL使用哪一个索引完成此次查询(仅仅是建议,mysql内部还会再次进行评估)。最后索引的选择取决于mysql。
explain select * from tb_user use index(idx_user_pro) where profession = '软件工程';
ignore index
:
忽略指定的索引。
explain select * from tb_user ignore index(idx_user_pro) where profession = '软件工程';
force index
:
强制使用索引。
explain select * from tb_user force index(idx_user_pro_age_sta) where profession = '软件