|
你能操作这个命令,告诉我为什么结果集只有两行吗?应该有三个,看起来像这样…# N3 X, h3 Y' L
appId stepId section start101 1 Section 2016年 -01-03 00:00:00.00010101 2 Section 2016年 2016-01-03 00:00:00.00010101 Section 3 NULL这是sql,因此,您可以将其粘贴到查询工具中0 t% y+ W4 d+ G; U" _. z5 S
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.startfrom #appSteps s with (nolock)left join #appProgress p on s.stepId = p.stepIdwhere s.section is not nulland p.appId = 101drop table #appStepsdrop table #appProgress我不知道为什么#appSteps三次非空行均未返回# D$ e3 v' x1 t& `* @$ [
: Y0 g- Y- I$ t1 [% n W
解决方案: 6 {1 J3 A3 l" Q& X. ^, K; h7 d- c
因为你在WHERE句子包含右表。您应将其移至以下内容。ON条件LEFT JOIN:& }3 @' u3 S; P2 J
Select P.appId,S.stepId,S.section,P.startFrom #appSteps S With (NoLock)Left Join #appProgress P On S.stepId = P.stepId And P.appId = 101Where S.section Is Not Null原因是,是的WHERE子句是 在后面 评估LEFT JOIN,然后过滤出你的NULL结果LEFT JOIN。
1 ^9 p$ Q: C! S* ], ]右手表包含在子句中LEFT JOIN(或左手表RIGHT JOIN)可将WHERE转换OUTER JOIN为INNER JOIN。 |
|