首页 > 解决方案 > Oracle:如果存在,我如何只返回第二个联合的行?

问题描述

我在 Oracle 中有两个选择与联合。我只想返回第二个联合的行,如果它返回任何东西,即使第一个联合也可能返回行。

我正在考虑使用 nvl,但我不确定如何实现它。

select 1 seq,
       x coord1,
       y coord2,
       z coord3
  from tableA a
 where a.prodRef = 4711
 union
select 2 seq,
       a coord1,
       b coord2,
       c coord3
  from tableB b
 where b.prodRef = 4711

现在 select 从带有 seq 1 和 seq 2 的查询中返回行。如果有来自带有 seq 2 的查询的输出,我只想查看这些数据(排除 seq 1 行),但是,可能存在 seq 2 的情况可能返回空行。当然,我这里只取seq 1的数据。

你们有任何想法如何解决这个问题吗?我的头脑完全是空的。

标签: sqloracleselect

解决方案


使用not exists

select 2 as seq, a as coord1, b as coord2, c as coord3
from tableB b
where b.prodRef = 4711
union all
select 1 as seq, x as coord1, y as coord2, z as coord3
from tableA a
where a.prodRef = 4711 and
      not exists (select 1 from tableB b where b.prodRef = a.prodRef);

推荐阅读