2016-10-17 39 views
2

你可以运行这个并告诉我为什么结果集只有两行。它应该有三个,看起来像这样...为什么我的t-sql左连接不起作用?

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 

我想不通为什么从所有3个非空行#appSteps不会回来

回答

6

原因是因为您在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 JOINNULL结果的原因。

包括WHERE子句中的一个LEFT JOIN的右侧表(或RIGHT JOIN的左侧表)有效地变换OUTER JOININNER JOIN

+1

非常感谢洙。这是工作 – Roto

+0

@Siyual好的解释。 –