您還會看到用於進一步過濾記錄的AND子句。在處理外連接時,這非常重要,因爲將這些過濾操作添加到caluse將從左連接變爲內連接的位置(除非它類似於t.idfield爲空的地方)。
下面我將展示這是如何工作的以及爲什麼將過濾類放在正確的位置非常重要。
創建表#TEST(test1id INT,測試VARCHAR(10)) 創建表#test2的(test2id INT,test1id INT,test2的VARCHAR(10))
insert into #test (test1id, test)
select 1, 'Judy'
union all
select 2, 'Sam'
union all
select 3, 'Nathan'
insert into #test2 (test2id, test1id, test2)
select 1,1,'hello'
union all
select 2,1,'goodbye'
union all
select 3,2,'hello'
select * from #test t
left join #test2 t2 on t.test1id = t2.test1id
where test2 = 'goodbye'
--result set
--test1id test test2id test1id test2
--1 Judy 2 1 goodbye
select * from #test t
left join #test2 t2 on t.test1id = t2.test1id
and test2 = 'goodbye'
--result set
--test1id test test2id test1id test2
--1 Judy 2 1 goodbye
--2 Sam NULL NULL NULL
--3 Nathan NULL NULL NULL
您可以使用其中的一些字段空(假設你選擇的永遠不會爲空字段)搶在第一個表中的記錄,但沒有第二個像這樣:
select * from #test t
left join #test2 t2 on t.test1id = t2.test1id
where test2id is null
--result set
--test1id test test2id test1id test2
--3 Nathan NULL NULL NULL
錯過「人四」浪費了我5分鐘:) – 2013-10-11 07:55:44