在SQL中显示两个表之间的差异

时间:2018-04-20 21:15:38

标签: sql-server tsql

我有两张桌子,我希望根据书名和版本来区分它们:

表1

id Name  version
1  B5077  A        
2  B5077  A     
4  B5077  B      
5  B5077  C

表2

id name  version
1  B5077  B        
2  B5077  C     
3  B5077  D      
4  B5077  E

SQL命令(与完整连接相比,结果非常快):

(   SELECT name, version FROM table 1 where book = 'B5077'
    EXCEPT
     SELECT name, version FROM table 2 )  
UNION ALL
(   SELECT name, version FROM table 2 where book = 'B5077'
    EXCEPT
    SELECT name, version FROM table 1) 

它给了我这个输出:

id name  version
1  B5077 A        
2  B5077 D     
3  B5077 E      

但我怎么能得到有差异的行的id和在哪个表中?所以我可以这样:

  id  name  version  idtable1  idtable2
   1  B5077 A        1         NULL 
   2  B5077 A        2         NULL
   3  B5077 D        NULL      3
   3  B5077 E        NULL      4

谢谢,

1 个答案:

答案 0 :(得分:1)

首先选择表1中不存在的表1中的行,然后添加表1中不存在的表2中的行。

select Name, Version, id as idtable1, null as idtable2
from Table1
where not exists (select * from Table2 where Table2.Name = Table1.Name and Table2.Version = Table1.version)
union
select Name, Version, null as idtable1, id as idtable2
from Table2
where not exists (select * from Table1 where Table1.Name = Table2.Name and Table1.Version = Table2.version)