Mysql-Join 关联查询之索引失效问题
案例分析
#常规查询 select po.columA, po.columB, tr.id bId from tableNameA tr inner join tableNameB po on tr.columC = po.columC and po.mark = 0 where tr.mark = 0 group by bId;
#执行计划
单数据量大的时候发现执行相当耗时。查看执行计划发现未走索引,经对比发现同一个字段在两个表A,B 中定义的字符集类型不同。
#其中columC 字段,在A,B表中均为索引字段 #A:表中columC 字段字符集为utf8类型,B:表中columC 字段字符集为utf8mb4_bin类型 #方式1修改字符集 后执行查询
alter table tableNameA modify `columC` varchar(32) NOT NULL DEFAULT '' COMMENT 'test';
alter table tableNameB modify `columC` varchar(32) COLLATE utf8mb4_bin NOT NULL DEFAULT '' COMMENT 'test';
select po.columA, po.columB, tr.id bId from tableNameA tr inner join tableNameB po on tr.columC = po.columC and po.mark = 0 where tr.mark = 0 group by bId;
#方式2 进行字符集转换后进行查询
select po.columA, po.columB, tr.id bId from tableNameA tr inner join tableNameB po on convert (tr.columC using utf8) = po.columC and po.mark = 0 where tr.mark = 0 group by bId;
相应执行计划
结论:
场景:当使用关联查询(inner 、left、right join)等进行查询时候,关联条件都已建立索引,但查看执行计划发现并未走索引。
原因:两表字段的字符集不相同导致关联查询索引失效
解决方案:1.修改表字段字符集类型,保证字符集一致