检查两个表之间的多个列中的唯一值

时间:2017-01-06 15:08:18

标签: sql sql-server outer-join

我正在尝试检查两个表中的多个列,以查看表之间的任何行是否匹配。这就是我现在只有1个列:

        SELECT *
        FROM   {table1} 
        FULL OUTER JOIN {table2} 
        ON table1.colum1 = table2.colum1
        WHERE table1.colum1 IS NULL
        OR table2.colum1 IS NULL

这就是我试过的2个字符串:

        SELECT *
        FROM   {table1} 
        FULL OUTER JOIN {table2} 
        ON table1.colum1 = table2.colum1 and table1.colum2 = table2.colum2
        WHERE table1.colum1 IS NULL and table1.colum
        OR table2.colum1 IS NULL and table2.colum2 IS NULL
这个doenst似乎有效。有人可以帮我一点吗?

表1中的数据:

---------
| 1 | 1 |
---------
| 2 | 2 |
---------
| 2 | 3 |
---------

我在表2中的数据:

---------
| 1 | 1 |
---------
| 2 | 3 |
---------
| 2 | 4 |
---------

预期结果:

   t1      t2
-----------------
| 2 | 2 | 2 | 4 |
-----------------

提前致谢

2 个答案:

答案 0 :(得分:3)

惯用的基于集合的方法是使用UNIONEXCEPT

declare @t1 table (i1 int,i2 int)
insert into @t1(i1,i2) values
(1,1),
(2,2),
(2,3)

declare @t2 table (i1 int,i2 int)
insert into @t2(i1,i2) values
(1,1),
(2,3),
(2,4)

(select i1,i2 from @t1
except
select i1,i2 from @t2)
union all
(select i1,i2 from @t2
except
select i1,i2 from @t1)

结果:

i1          i2
----------- -----------
2           2
2           4

答案 1 :(得分:0)

这应该可以解决问题:

SELECT coalesce(table1.col1, table2.col1) as col1
   , coalesce(table1.col2, table2.col2) as col2
FROM table1
FULL OUTER JOIN table2
    ON table1.col1 = table2.col1 and table1.col2 = table2.col2
WHERE (table1.col1 IS NULL and table1.col2 IS NULL)
    OR (table2.col1 IS NULL and table2.col2 IS NULL)