且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么我的 t-sql 左连接不起作用?

更新时间:2022-03-07 23:07:01

原因是因为您在 WHERE 子句中包含了右侧表.您应该将其移至 LEFT JOINON 条件:

The reason is because you are including the right-hand table in the WHERE clause. You should move that to the ON condition of the LEFT JOIN:

Select    P.appId, S.stepId, S.section, P.start
From      #appSteps    S   With (NoLock)
Left Join #appProgress P   On  S.stepId = P.stepId 
                           And P.appId = 101
Where     S.section Is Not Null

这样做的原因是因为 WHERE 子句在 LEFT JOIN 之后被评估,然后过滤掉你的 NULL 来自 LEFT JOIN 的结果.

The reason it does this is because the WHERE clause is evaluated after the LEFT JOIN, which then filters out your NULL results from the LEFT JOIN.

WHERE 子句中包含 LEFT JOIN 的右侧表(或 RIGHT JOIN 的左侧表)有效地将 OUTER JOIN 转换为 INNER JOIN.

Including the right-hand table of a LEFT JOIN (or the left-hand table of a RIGHT JOIN) in the WHERE clause effectively transforms the OUTER JOIN into an INNER JOIN.