首页 > 解决方案 > 如何强制连接的顺序以提高 MYSQL 中的查询性能?

问题描述

我有一个sql语句

SELECT count(*)
From table1 
inner join table2 on condition1
..
inner join tableN on conditionN-1
inner join problematic_table on tableN.FKColumn= problematic_table.FKColumn

这会产生 20-25 秒的结果。

如果我像这样运行查询,它会运行得更快。在 100 毫秒内

select count(*)
from problematic_table where problematic_table.FKColumn in (
select distinct tableN.FKColumn
    From table1 
    inner join table2 on condition1
    ..
    inner join tableN on conditionN-1
)

我想指出,从 table1 到 tableN 的表连接没有结果(为空)。

那么为什么第一种情况下的性能那么差呢?

编辑: 运行 EXPLAIN 时,表的排序顺序与我在 JOIN 中编写的顺序不同

EDIT2 所以对于第一个查询,problemati_table 连接不是最后运行,而是实际将行数减少到 0 的查询最后运行。对于第二个查询是相同的顺序,除了有问题的表在顶部,id=1 和 select_type=Primary,其他是 id=2 和 select_type=MATERIALIZED。

所以我想问题变成了如何让引擎按照我写的顺序运行查询?

编辑3

可能的情况是引擎最后运行的连接条件是 TABLE1 和 TABLE2,它们的形式为:

SELECT
FROM TABLE1
INNER JOIN TABLE2 on TABLE1.COLUMN1='constant_string' and TABLE2.COLUMN2='constant_string2'
INNER JOIN ... other tables have proper join conditions between colums of the tables.

EDIT4 更改了问题的标题以吸引可能面临相同问题的其他人。

标签: mysqlsqlquery-performancesqlperformance

解决方案


问题是引擎运行连接的顺序很糟糕。我通过使用STRAIGHT_JOIN优化器提示而不是简单的方法解决了这个问题INNER JOIN


推荐阅读