你可以运行它并告诉我为什么结果集只有两行。它应该有三个,看起来像这样......
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个非空行都没有返回
答案 0 :(得分:10)
原因是您在WHERE
子句中包含了右侧表格。您应该将其移至ON
的{{1}}条件:
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
之后评估,然后从{{1}过滤出LEFT JOIN
个结果}}
在NULL
子句中包含LEFT JOIN
的右侧表格(或LEFT JOIN
的左侧表格)有效地将RIGHT JOIN
转换为{ {1}}。