如何强制联接的顺序以提高MYSQL的查询性能?

问题描述 投票:0回答:1

我有一条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
)

我想指出的是,从表1到表N的表联接没有结果(为空)。

所以为什么在第一种情况下的性能这么差?

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

EDIT2

因此,对于第一个查询,problemati_table连接不会最后运行,但实际上将行数减少到0的查询最后运行。对于第二个查询,除了问题表位于顶部之外,其他顺序相同id = 1和select_type = Primary,其他则是id = 2和select_type = MATERIALIZED。

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

EDIT3

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

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

EDIT4

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

我有一条sql语句SELECT count(*)从condition1的table1内部联接table2 .. conditionN-1的内部联接tableN在tableN.FKColumn = problematic_table.FKColumn ...

mysql sql query-performance sqlperformance
1个回答
1
投票
问题是,发动机的运转顺序不佳。我使用STRAIGHT_JOIN优化程序提示而不是简单的INNER JOIN解决了此问题
© www.soinside.com 2019 - 2024. All rights reserved.