获取仅在两个表之一中的值

时间:2016-06-24 10:06:35

标签: sql oracle

我想获取两个表中没有的记录。说我有表A:

100
120
140

和表B:

100
110
130

我想获取显示在两个表中的值,但不是两者都是:

120
140
110
130

1 个答案:

答案 0 :(得分:0)

我可以想到三个方面,可能还有其他方法。我认为,最接近您的尝试,结合您运行的两个单独的查询:

select num from a
minus select num from b
union all
(
  select num from b
  minus select num from a
);

或者只打一次每个表::

select num
from(
  select num from a
  union all
  select num from b
)
group by num
having count(*) < 2;

或者:

select coalesce(a_num, b_num)
from (
  select a.num a_num, b.num b_num
  from a
  full outer join b on b.num = a.num
)
where a_num is null or b_num is null;

这三个都会对您的数据产生相同的结果。一个使用CTE提供您的价值观的演示:

with a (num) as (
  select 100 from dual
  union all select 120 from dual
  union all select 140 from dual
),
b (num) as (
  select 100 from dual
  union all select 110 from dual
  union all select 130 from dual
)
select coalesce(a_num, b_num) as num
from (
  select a.num a_num, b.num b_num
  from a
  full outer join b on b.num = a.num
)
where a_num is null or b_num is null;

       NUM
----------
       110
       130
       140
       120