简体   繁体   English

具有多个 JOINS 子查询的 MySQL 查询中的执行顺序

[英]Order of execution in MySQL query with multiple JOINS of subqueries

I have the following query with a LEFT JOIN between the first two subqueries e and a , and an INNER JOIN between the last two subqueries a and m :我有以下查询,前两个子查询ea之间有一个LEFT JOIN ,最后两个子查询am之间有一个INNER JOIN

SELECT {cols}
FROM 
(SELECT {cols}
 FROM {table} 
 WHERE {conditions}) AS e
LEFT JOIN
(SELECT {cols}
 FROM {table} 
 WHERE {conditions}) AS a
ON e.col = a.col
INNER JOIN
(SELECT {cols}
 FROM {table} 
 WHERE {conditions}) AS m
ON e.col = m.col

When I change the second join from INNER JOIN to LEFT JOIN , the execution time increase by a factor of ~200 .当我将第二个连接从INNER JOIN更改为LEFT JOIN时,执行时间增加了~200倍。 The number of records from each subquery is as follows:每个子查询的记录数如下:

e -> Number of records: 303
a -> Number of records: 18
m -> Number of recordings: 295

I assumed MySQL would evaluate each subquery as an independent subquery and then do the joins, in which case, the change from INNER JOIN to LEFT JOIN should not lead to such an increase in the execution time given the relatively low number of records as shown above.我假设 MySQL 会将每个子查询评估为一个独立的子查询,然后执行连接,在这种情况下,从INNER JOINLEFT JOIN的更改不应导致执行时间增加,因为记录数量相对较少,如上所示.

So, obviously it seems that's not the execution order being followed.因此,显然这似乎不是遵循的执行顺序。

EXPLAIN PLAN :解释计划

Case 1 with INNER JOIN: join e with m first, then join with a. 
Case 2 with LEFT JOIN: join e with a first, then join with m. 

I'm not sure why the two plans are different in the two cases and how this might lead to a difference in the execution time.我不确定为什么这两个计划在这两种情况下不同,以及这如何导致执行时间不同。

Can anyone help explain to me what the actual execution order may be?谁能帮我解释一下实际的执行顺序是什么?

The join order is up to the query planner to optimize as it sees fit.连接顺序由查询计划器决定,以在它认为合适时进行优化。 Sometimes it gets it wrong.有时它会弄错。 If you think the join order is suboptimal you can force it by specifying SELECT STRAIGHT_JOIN instead of SELECT .如果您认为加入顺序不是最优的,您可以通过指定SELECT STRAIGHT_JOIN而不是SELECT来强制执行。 This will force the query planner to join tables in the order listed in the query.这将强制查询规划器按照查询中列出的顺序连接表。

Outer joins are always going to be slower because they have to scan more rows - they cannot discard rows that don't match in both sides.外连接总是会变慢,因为它们必须扫描更多的行——它们不能丢弃两边都不匹配的行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM