从oracle sql中的Minus操作中排除列

时间:2014-08-12 08:34:49

标签: sql oracle

我想知道您是否可以从MINUS操作中排除列

例如:

select column 1, column 2, column 3
from table 1

minus

select column 1, column 2
from table 2;

第3列被排除在操作之外。

有没有这样做?

谢谢

3 个答案:

答案 0 :(得分:5)

你有几个选择。

<强>#1

没有column3的减号然后将结果重新加入到原始表中以获取column3的缺失值。

select *
from (
        select column1, column2
        from table1
        minus
        select column1, column2
        from table2
    )
join table1 using (column1, column2)

<强>#2

使用ANTI-JOIN NOT EXISTS子句应该和NOT IN一样工作。

select column1, column2, column3
from table1
where (column1, column2) not in (
        select column1, column2
        from table2
)

答案 1 :(得分:0)

也许你是在追求这个?

select table1.column1, table1.column2, table1.column3
from table1
left table2 on table1.column1 = table2.column1 and table1.column2 = table2.column2
where table1.id IS NULL

这将导致只有那些table1记录在table2中没有匹配的column1和column2值。

答案 2 :(得分:-1)

看看这个:

with t(a, b, c) as (
  select 1, 2, 3 from dual union all
  select 2, 2, null from dual union all
  select 2, 3, 5 from dual
), t1(a, b) as (
  select 1, 2 from dual union all
  select 2, 2 from dual union all
  select 2, 3 from dual
), t2 as (
  select a, b, c from t
  minus
  select a, b, null from t1
)
select a, b from t2

A   B
-----
1   2
2   3

SQLFiddle

如果你的column3中有空值而你想要转义它们,你可以像这样转义它们:

with t(a, b, c) as (
  select 1, 2, 3 from dual union all
  select 2, 2, null from dual union all
  select 2, 3, 5 from dual
), t1(a, b) as (
  select 1, 2 from dual union all
  select 2, 2 from dual union all
  select 2, 3 from dual
), t3 as (
  select a, b, nvl(c, -1) from t
  minus
  select a, b, null from t1
)
select a, b from t3

A   B
-----
1   2
2   2
2   3

SQLFiddle