2016-12-14 79 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 
相关问题