2016-10-17 9 views
2

これを実行して、結果セットに2行しかない理由を教えてください。それはあなたがちょうどあなたのクエリツールに貼り付けることができ私のt-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つのnull以外の行を把握することはできませんので、ここで

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です... 3を持っているし、次のようになります。 #appステップが戻ることはありません。

答えて

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からあなたNULL結果をフィルタリングLEFT JOINを、評価されるため、これがありません理由を。 WHERE句のLEFT JOINの右側のテーブル(又はRIGHT JOINの左側のテーブル)を含む、

を効果INNER JOINOUTER JOINを変換します。

+1

ありがとうsoo。それは働いています – Roto

+0

@Siyual良い説明だけでなく。 –

関連する問題