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
中。但我感覺不好,這並不總是給出正確的結果。其實真正的完整查詢的性能非常差。