Mysql-Join 關聯查詢之索引失效問題


mysql 關聯查詢時,索引失效問題

案例分析

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

       2.使用convert()函數,保證關聯的索引字段 轉換后兩邊字符集一致


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM