【问题标题】:Why is my t-sql left join not working?为什么我的 t-sql 左连接不起作用?
【发布时间】:2021-11-11 21:59:42
【问题描述】:

你能运行这个并告诉我为什么结果集只有两行。它应该有三个,看起来像这样......

appId    stepId       section       start
101      1           Section 1     2016-01-03 00:00:00.000
101      2           Section 2     2016-01-03 00:00:00.000
101      10          Section 3     NULL

这是 sql,因此您可以将其粘贴到查询工具中

create table #appSteps(stepId decimal, section nvarchar(50))
insert into #appSteps (stepId, section) values (1, 'Section 1')
insert into #appSteps (stepId, section) values (2, 'Section 2')
insert into #appSteps (stepId, section) values (3, null)
insert into #appSteps (stepId, section) values (4, null)
insert into #appSteps (stepId, section) values (10, 'Section 3')

create table #appProgress(stepId decimal, appId int, start datetime)
insert into #appProgress (stepId, appId, start) values (1, 101, '1/3/2016')
insert into #appProgress (stepId, appId, start) values (2, 101, '1/3/2016')
insert into #appProgress (stepId, appId, start) values (3, 101, '1/3/2016')
insert into #appProgress (stepId, appId, start) values (4, 101, '1/3/2016')


select p.appId, s.stepId, s.section, p.start
from #appSteps s with (nolock)
left join #appProgress p on s.stepId = p.stepId
where s.section is not null
and p.appId = 101

drop table #appSteps
drop table #appProgress

我无法弄清楚为什么#appSteps 中的所有 3 个非空行都没有返回

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

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

    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 之后进行评估,然后从LEFT JOIN 中过滤掉您的NULL 结果。

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

    【讨论】:

    • @Siyual 解释也很好。
    • @Siyal,许多搜索都没有包含这些重要信息。谢谢!!!
    • 我一直在为此拉头发。谢谢你的解释!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多