SQL Server查询在两个表中查找不同的名称

时间:2013-06-21 11:48:18

标签: sql sql-server-2008

我有一个情况。

我有两张桌子:

enter image description here

我需要一个sql查询,它将打印两个表中不同的Col名称。

例如,在这种情况下,查询应将结果打印为:

enter image description here

原因很清楚,表{1中存在m但表2中没有。类似于表{2中的z而不是表-1中的情况。

我真的很高兴,请帮忙。

列名称不区分大小写。

感谢。

6 个答案:

答案 0 :(得分:1)

您也可以使用NOT EXISTS来获得结果:

select col1
from table1 t1
where not exists (select 1
                  from table2 t2
                  where t1.col1 = t2.col1)
union all
select col1
from table2 t2
where not exists (select 1
                  from table1 t1
                  where t1.col1 = t2.col1);

请参阅SQL Fiddle with Demo

甚至不是IN:

select col1
from table1 t1
where col1 not in (select col1
                   from table2 t2)
union all
select col1
from table2 t2
where col1 not in (select col1
                   from table1 t1);

请参阅SQL Fiddle with Demo

答案 1 :(得分:0)

尝试:

select coalesce(t1.Col1, t2.Col1)
from [Table-1] t1
full outer join [Table-2] t2 on t1.Col1 = t2.Col1
where t1.Col1 is null or t2.Col1 is null

SQLFiddle here

可替换地:

select Col1 from
(select Col1 from [Table-1] union all select Col1 from [Table-2]) sq
group by Col1 having count(*) = 1

SQLFiddle here

答案 2 :(得分:0)

我认为最简单的就是这个

SELECT COL1 AS ResultCol FROM TABLE1 where COL1 not in (select COL2 from TABLE2) UNION SELECT COL2 AS ResultCol FROM TABLE2 where COL2 not in (select COL1 from table1)

答案 3 :(得分:0)

declare @tab1 table(id int,col1 varchar(1))
declare @tab2 table(id int,col1 varchar(1))
INSERT INTO @tab1
    ([id], [Col1])
VALUES
    (1, 'A'),
    (2, 'B'),
    (3, 'm'),
    (4, 'c')

INSERT INTO @tab2
    ([id], [Col1])
VALUES
    (1, 'A'),
    (2, 'B'),
    (3, 'C'),
    (4, 'z')





select b.id,b.col1 from
(
select a.id,a.col1,b.col1 x from @tab1 a left join @tab2 b on a.col1 = b.col1
union
select b.id,b.col1,a.col1 x from @tab1 a right join @tab2 b on a.col1 = b.col1
 ) b
where b.x is null

答案 4 :(得分:0)

这项操作专门有一项功能。除了和拦截。

查找以下查询中不存在哪些值(单列结果或多列结果)

- 表A中的内容不在表B中

SELECT col1 FROM TableA
EXCEPT
SELECT col1 FROM TableB

- 表B中没有表A中的内容

SELECT col1 FROM TableB
EXCEPT
SELECT col1 FROM TableA

同样,INTERCEPT关键字会告诉您共享的内容

- 表A和表B中的内容

SELECT col1 FROM TableA
INTERCEPT
SELECT col1 FROM TableB

答案 5 :(得分:0)

您也可以使用FULL OUTER JOIN运算符。 Visual Representation of SQL Joins

SELECT ROW_NUMBER() OVER(ORDER BY COALESCE(t1.Col1, t2.Col1)) AS id,       
       COALESCE(t1.Col1, t2.Col1) AS ResultCol
FROM Table1 t1 FULL JOIN Table2 t2 ON t1.Col1 = t2.Col1
WHERE t1.Col1 IS NULL OR t2.Col1 IS NULL

请参阅SQLFiddle

上的示例