join语句的操作顺序

2021-12-17 00:00:00 join sql left-join tsql sql-server

给定以下 3 种方式加入

Given the following 3 way join

select t1.* from t1
left join t2 on t1.fk = t2.pk
join t3 on t2.fk = t3.pk

如果 t2 和 t3 之间的连接失败,是否会返回 t1 和 t2 之间成功连接的行?如果操作顺序是从左到右,我假设不是,但如果它是从右到左计算的(t3 先连接到 t2),那么即使前者失败,t1 仍将返回.

If the join between t2 and t3 failed, would the row from the successful join between t1 and t2 be returned? If the order of operation goes from left to right, I assume not, but if it's evaluated from right to left (t3 is joined to t2 first) then t1 will still be returned even when the former failed.

它是如何工作的?

推荐答案

ON 子句的位置控制评估的逻辑顺序.

The placement of the ON clauses controls the logical order of evaluation.

所以首先 t1 LEFT JOIN t2 ON t1.fk = t2.pk 发生.此连接的结果是一个包含 t1, t2 中所有匹配行的虚拟表,并且(因为它是左外连接)任何不匹配的 t1 行也被保留t2 列的空值.

So first the t1 LEFT JOIN t2 ON t1.fk = t2.pk happens. The result of this join is a virtual table containing all the matching rows from t1, t2 and (because it is a left outer join) any non matched t1 rows are also preserved with null values for the t2 columns.

这个虚拟表然后参与下一个连接.在 t2.fk = t3.pk 上加入 t3

This virtual table then participates in the next join. JOIN t3 ON t2.fk = t3.pk

任何与 t1 中的行不匹配的 t2 记录都不是第一阶段的虚拟表输出的一部分,因此不会出现在最终结果中.此外,在 t2.fk = t3.pk 上的这个内部连接将丢失 t2.fk 的任何 NULL 值,有效地将你的整个事情重新变成内部加入.

Any t2 records that do not match rows in t1 are not part of the virtual table output from the first stage so won't appear in the final result. Additionally this inner join on t2.fk = t3.pk will lose any NULL values of t2.fk effectively turning your whole thing back into inner joins.

逻辑查询处理解释得很好作者:Itzik Ben Gan 在这里

Logical Query Processing is explained well by Itzik Ben Gan here

相关文章