mysql - 如何强制连接的顺序以提高 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 更改了问题的标题以吸引可能面临相同问题的其他人。
解决方案
问题是引擎运行连接的顺序很糟糕。我通过使用STRAIGHT_JOIN
优化器提示而不是简单的方法解决了这个问题INNER JOIN
推荐阅读
- javascript - 对象函数返回函数局部变量而不是对象变量?
- r - “错误:美学必须是长度 1 或与数据相同 (164)”
- r - 闪亮的应用程序错误:“$ 中的错误:$ 运算符对原子向量无效”
- pine-script - 如何覆盖 Pine Script 指示器,但让它根据左侧的百分比比例(100% 到 -100%)显示?
- godot - GODOT - 使用 connect() 时信号未连接。函数未执行
- scala - 为什么 sortWith(lt: (A, A) => Boolean) 需要一个具有两个参数的函数,但可以使用只有一个参数的 compareTo?
- mobile - Appium 检查器总是在加载
- javascript - Leaflet-groupedlayercontrol 在 R 中使用图层组
- c++ - 编译 Curl 和 GTK
- python - 如何列出我的存储库中的所有文件夹和文件