2016-12-14 56 views
1

我有兩個表,我想比較。首先它必須比較test1列。如果第一個表中有一個值存在於第二個表中,反之亦然,則必須在結果中顯示這些值。這需要爲每一列完成。檢查列的組合是否匹配在這兩個表

例如:

first table: 
------------------------------ 
| id | test1 | test2 | test3 | 
------------------------------ 
| 1 | 1  | 1  | 1  | 
------------------------------ 
| 2 | 2  | 2  | 3  | 
------------------------------ 
| 3 | 3  | 3  | 3  | 
------------------------------ 
| 4 | 3  | 3  | 3  | 
------------------------------ 

second table: 
------------------------------ 
| id | test1 | test2 | test3 | 
------------------------------ 
| 1 | 1  | 1  | 1  | 
------------------------------ 
| 2 | 2  | 2  | 2  | 
------------------------------ 
| 3 | 3  | 3  | 3  | 
------------------------------ 
| 4 | 3  | 3  | 3  | 
------------------------------- 
| 5 | 3  | 9  | 3  | 
------------------------------ 

那麼結果將是:

------------------------------ 
| id | test1 | test2 | test3 | 
------------------------------ 
| 2 | 2  | 2  | *2* | 
------------------------------ 
| 2 | 2  | 2  | *3* | 
------------------------------ 
| 5 | 3  | *9* | 3  | 
------------------------------ 

到現在,我得到了這個過程的代碼是:

SELECT dbo.first.[test1], dbo.first.[test2], dbo.first.[test3], 
dbo.second.[test1], dbo.second.[test2], dbo.second.[test3] 
FROM dbo.first left join dbo.second on 
dbo.first.[test1]=dbo.second.[test1] and 
dbo.first.[test2]=dbo.second.[test2] and 
dbo.first.[test3]=dbo.second.[test3] 

但這個心不是表現正確的結果。

在此先感謝您的幫助。

回答

3

因爲您正在處理所有列,所以exceptminus是最簡單的方法。它看起來像你正在使用SQL Server,所以:

select * 
from (select t1.* from t1 
     except 
     select t2.* from t2 
    ) tt 
union all 
select * 
from (select t2.* from t2 
     except 
     select t1.* from t1 
    ) tt 
相關問題