这两天在公司优化一个sql的时候碰到了一个诡异的事——一个表中的一个唯一性索引在更换了最左边的字段后,根据最左边字段为where后面的查询条件时,查看执行计划发现有些时候有用到索引,而有些时候则没有用到索引。

现象具体说明

出现问题的表结构以及其字符集如下:

alter table sodr_po_header add UNIQUE KEY sodr_po_header_u1(po_num, po_type_id, snapshot_flag,tenant_id);
show index from sodr_po_header;
explain select * from sodr_po_header where po_num = 'PO20190619000014';// 复合索引的最左字段

执行上面的sql语句后,有如下结果:sodr_po_header表的索引为:

执行计划结果为:
显然此时是根据索引进行查找的。

然后更换复合索引字段顺序:

drop index sodr_po_header_u1 on sodr_po_header;

alter table sodr_po_header add UNIQUE KEY sodr_po_header_u1(po_type_id, po_num, snapshot_flag,tenant_id);
show index from sodr_po_header;
explain select * from sodr_po_header where po_type_id = 9; // 复合索引的最左字段

执行上面4条sql后,表的索引情况:

执行计划结果:
此时执行计划显示并未使用索引进行查找。

为什么会有上面这种现象

如上,为了找到会出现这种“bug”的原因,我额外建了一张表teacher用于测试,其表结构和字符集如下:

alter table teacher add UNIQUE KEY dept_uk_tt(tname, tid, gender);
show index from teacher;
explain select * from teacher where tname = 'tw'; // 复合索引最左字段

teacher表的索引情况:

执行计划结果:
此时是有用到索引的。

更换复合索引中字段的顺序:

drop index dept_uk_tt on teacher;
alter table teacher add UNIQUE KEY dept_uk_tt(tid, tname, gender);
show index from teacher;
explain select * from teacher where tid = 3; // 复合索引最左字段

teacher表的索引情况:

执行计划结果:
发现还是用到了索引进行查询操作,这个时候真的只能用上“震惊”二字了。

总结

目前我还是没有什么头绪,如果有大佬看到了这篇文章并且有解决方案或者任何提议,希望在评论里给我留言。当然,如果我找到了原因,同样会更新本文。