如何删除两个表中的公共字段

时间:2013-10-08 08:03:45

标签: sql join duplicate-removal

我有两个表,表1和表2.

表1的字段是: book,pen,pencil,bag

表2的字段是: car,van,book,bike,pencil

当我运行查询时,我希望查询忽略重复或公共字段并返回其他字段。

输出应如下,

car,van,bike,pen,bag

4 个答案:

答案 0 :(得分:2)

也许:

SELECT x.thing FROM
(
    SELECT thing FROM dbo.Table1
    UNION ALL
    SELECT thing FROM dbo.Table2
) X
GROUP BY x.thing
Having Count(*) = 1

Demo

但是,这也会删除表格中可能重复或可能不需要的重复项目。

答案 1 :(得分:0)

你试过这样的事吗:

delete form X
where (car  = 
    Select distinct car
    from X 
    where x);

不同 - >返回不同的值。

答案 2 :(得分:0)

    WITH uniontables AS  (
  SELECT    NULL AS car,
            NULL AS van,
            book,
            NULL AS bike,
            pen,
            pencil,
            bag 
  FROM      [Table 1 ]
  UNION 
  SELECT    car,
            van,
            book,
            bike,
            NULL AS pen,
            pencil,
            NULL AS bag 
  FROM [Table 2 ] )

  SELECT DISTINCT * FROM uniontables

答案 3 :(得分:0)

试试这个:

declare @table1 table (col1 varchar(max))
declare @table2 table (col1 varchar(max))

insert into @table1 values
('book'),('pen'),('pencil'),('bag')

insert into @table2 values ('car'),('van'),('book'),('bike'),('pencil') 

;with cte
as (
select COUNT(1) as total_item, col1 from (
select col1 from @table1
union all 
select col1 from @table2
)a group by col1
)

select  col1 from cte  where total_item = 1