案例分析
#常規查詢 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.修改表字段字符集類型,保證字符集一致