如何比较两个表并显示每个差异

时间:2017-01-05 14:25:25

标签: mysql sql sql-server compare

我每两列有两张桌子。我想比较这些列,看看它们是否相同。这两个表看起来像这样:

表一:

-----
| 1 |
-----
| 2 |
-----
| 3 |
-----
| 4 |    
-----
| 5 |
-----
| 6 |
-----
| 7 |
-----
| 8 |
-----
| 9 |
-----

表二:

----- <-- missing `1` in table 
| 2 |
----- <-- missing `3` in table 
| 4 |    
-----
| 5 |
-----
| 5.5 | <-- extra `5.5` in table 
-----
| 6 |
-----
| 8 | <-- this one isnt the same as the `7` in table one
-----
| 7 | <-- this one isnt the same as the `9` in table one
-----
| 9 |
-----

SQL查询应返回如下表:

-----------------
| Table1| Table2|
----- -----------
| 1     |       |
----- -----------
| 3     |       |
-----------------
|       | 5.5   |
-----------------
| 7     | 8     |
-----------------
| 8     | 7     |
-----------------

因此,如果一个值仅存在于其中一个表中,则需要为selected。另外,如果在表2中,前一个字符串之后的字符串与表1中前一个字符串之后的字符串不同,则需要为selected

2 个答案:

答案 0 :(得分:1)

使用FULL OUTER JOIN

SELECT *
FROM   Table1 t1
       FULL OUTER JOIN Table2 t2
                    ON t1.col = t2.col
WHERE  t1.col IS NULL
        OR t2.col IS NULL 

如果您的DBMS不支持FULL OUTER JOIN,那么

SELECT *
FROM   Table1 t1
       LEFT JOIN Table2 t2
                    ON t1.col = t2.col
WHERE  t2.col IS NULL
Union all
SELECT *
FROM   Table1 t1
       Right JOIN Table2 t2
                    ON t1.col = t2.col
WHERE  t1.col IS NULL

答案 1 :(得分:1)

您需要全外连接

select *
from mytable1 a1
full outer join mytable2 a2
on a1.mycolumn = a2.mycolumn

仅显示缺少的那些,添加:

where a1.mycolumn is null
or a2.mycolumn is null