如何强制连接顺序以提高mysql中的查询性能?

1tuwyuhd  于 2021-07-29  发布在  Java
关注(0)|答案(1)|浏览(294)

我有一个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\u table join不是最后运行的,而是实际将行数减少到0的查询最后运行。对于第二个查询,除了有问题的\u表位于顶部,id=1,并选择\u type=primary,其他的都是id=2,并选择\u type=materialized。
所以我想问题是如何让引擎按照我写查询的顺序运行查询?
编辑3
可能的情况是,引擎最后运行的联接条件是表1和表2,其形式如下:

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更改了问题的标题,以吸引可能面临相同问题的其他人。

3zwjbxry

3zwjbxry1#

问题是引擎按顺序运行联接,但执行得不好。我通过使用 STRAIGHT_JOIN 优化器提示而不是简单提示 INNER JOIN

相关问题