当我在oracle中减去两个表时如何获取所有值

时间:2014-03-17 16:11:57

标签: sql oracle

我有两个表,例如table1和table2

table1有重复的行,但table2可能有也可能没有 当我做的时候

select * from table1 minus select * from table2

我获得了table1的唯一值,但我需要重复值

1 个答案:

答案 0 :(得分:3)

如果您有一个键(一个或多个字段可以让您知道table1中的一行是否与table2中的另一行匹配),您可以使用exist

select *
from table1 t1
where not exists (select 1 from table2 t2 where t2.pk_field = t1.pk_field)

如果您没有PK,则必须指定所有字段:

select *
from table1 t1
where not exists (select 1 from table2 t2 where t2.field1 = t1.field1
                                            and t2.field2 = t1.field2 ...)

编辑:这是一个基本示例:

with table1 as
(
  select 1 a from dual
  union all
  select 1 a from dual
  union all
  select 2 a from dual
  union all
  select 2 a from dual
  union all
  select 3 a from dual
),
table2 as
(
  select 2 a from dual
)
select *
from table1 t1
where not exists (select 1 from table2 t2 where t2.a = t1.a)

结果是正确的,1显示两次:

Row #   A
1   1
2   1
3   3