2011-06-14 42 views
1

On-Clause-Criteria依賴於兩列中的任意一列時,(內連接)兩個表的正確方法是什麼?因此,Table1應該在兩列中的任何一列等於Table2的一列時連接。內連接的ON子句中的附加「Or-Criteria」

看一看下面的簡化T-SQL,看看我的意思是,如果我做這些是正確的方法:

SET TRANSACTION ISOLATION LEVEL READ COMMITTED 
GO 
BEGIN TRANSACTION; 
GO 
create table #RMA1(
    SSN_IN varchar(15), 
    SSN_OUT varchar(15) 
) 
create table #RMA2(
    SSN_NUMBER varchar(15), 
) 
INSERT INTO #RMA1 VALUES('012590001827977', '351600035840752'); 
INSERT INTO #RMA1 VALUES('332653577440220', '351600035804105'); 
INSERT INTO #RMA1 VALUES('350302031074780', '350302031074780'); 
INSERT INTO #RMA1 VALUES('351649036778024', '351806033440194'); 

INSERT INTO #RMA2 VALUES('012590001827977'); 
INSERT INTO #RMA2 VALUES('332653577440220'); 
INSERT INTO #RMA2 VALUES('350302031074780'); 
INSERT INTO #RMA2 VALUES('351649036778024'); 
INSERT INTO #RMA2 VALUES('351600035840752'); 
INSERT INTO #RMA2 VALUES('351600035804106'); 

SELECT SSN_IN,SSN_OUT,SSN_NUMBER FROM #RMA1 INNER JOIN 
#RMA2 ON (#RMA1.SSN_IN = #RMA2.SSN_NUMBER OR 
      #RMA1.SSN_Out = #RMA2.SSN_NUMBER) 

DROP TABLE #RMA1; 
DROP TABLE #RMA2; 
GO 
COMMIT TRANSACTION; 
GO 

結果:

SSN_IN   SSN_OUT   SSN_NUMBER 
012590001827977 351600035840752 012590001827977 
012590001827977 351600035840752 351600035840752 
332653577440220 351600035804105 332653577440220 
350302031074780 350302031074780 350302031074780 
351649036778024 351806033440194 351649036778024 

問:因此,在ON中加入OR的表格是否正確 - 使用內部連接?

它確實會正確返回5條記錄並刪除#RM2的最後一條記錄,因爲它既不在#RM1.SSN_IN也不在#RM1.SSN_OUT中。但我感覺不好,這並不總是給出正確的結果。其實真正的完整查詢的性能非常差。

回答

3

結果應該是正確的,但你的觀察是正確的,表現是不好的。數據庫不能有效地使用索引,因爲它必須掃描索引並對每個項目進行算術運算。

使兩個左聯接,而不是先給數據庫更好地利用索引:

select 
    SSN_IN, 
    SSN_OUT, 
    coalesce(T1.SSN_NUMBER, T2.SSN_NUMBER) as SSN_NUMBER 
from 
    #RMA1 
    left join #RMA2 as T1 on #RMA1.SSN_IN = T1.SSN_NUMBER 
    left join #RMA2 as T2 on #RMA1.SSN_Out = T2.SSN_NUMBER 
where 
    T1.SSN_NUMBER is not null or T2.SSN_NUMBER is not null