我有一个复杂的 MySQL 查询,它连接三个表并将一个表自连接到自身。
有一个 Master 和一个 Slave 具有相同的数据和索引。与 Slave 相比,Master 是一个强大的盒子,但查询在 Slave 上的运行速度要快 10 倍(在 Master 的轻负载期间)。
执行计划大不相同。
Master execution plan
1, 'SIMPLE', 'table3_', 'const', 'PRIMARY', 'PRIMARY', '12', 'const', 1, 100.00, 'Using temporary; Using filesort'
1, 'SIMPLE', 'table2_', 'ref', 'PRIMARY,FK376E02E910238FCA', 'FK376E02E910238FCA', '13', 'const', 105, 100.00, 'Using where'
1, 'SIMPLE', 'table0_', 'ref', 'FK57012F937DD0DC02,FK57012F9398CD28D0', 'FK57012F9398CD28D0', '13', 'table2_.ID', 1515, 100.00, 'Using where'
1, 'SIMPLE', 'table1_', 'eq_ref', 'PRIMARY,FKE7E81F1ED170D4C9', 'PRIMARY', '8', 'table0_.FK_ID', 1, 100.00, 'Using where'
Slave execution plan
1, 'SIMPLE', 'table3_', 'const', 'PRIMARY', 'PRIMARY', '12', 'const', 1, 100.00, 'Using filesort'
1, 'SIMPLE', 'table1_', 'ref', 'PRIMARY,FKE7E81F1ED170D4C9', 'FKE7E81F1ED170D4C9', '9', 'const', 187398, 100.00, 'Using where'
1, 'SIMPLE', 'table0_', 'ref', 'FK57012F937DD0DC02,FK57012F9398CD28D0', 'FK57012F937DD0DC02', '9', 'table1_.ID', 1, 100.00, 'Using where'
1, 'SIMPLE', 'table2_', 'eq_ref', 'PRIMARY,FK376E02E910238FCA', 'PRIMARY', '12', 'table0_.FK_ID', 1, 100.00, 'Using where'
这些表以不同的顺序处理,主数据库使用临时表和文件排序,而从属仅使用文件排序。
哪些因素会导致执行时间差异如此之大的不同计划?
更新:
这可能与索引统计有关吗?我计划在低容量期间在 Master 上运行 ANALYZE TABLE。SHOW INDEX 显示 Master 和 Slave 之间的某些键的非常不同的基数。