ORACLE中的INTERSECT(SQL不是PL / SQL)

时间:2017-12-14 10:15:07

标签: sql oracle

我必须在两个select语句之间执行INTERSECTION。只有当两个select语句都返回一些结果集时,才会发生交叉条件。如果任何一个返回O行,则Intersection不起作用,最终结果必须是返回某些行的语句。这可能在SQL中(我不需要pl/sql中的答案)吗?

1 个答案:

答案 0 :(得分:1)

您可以使用此结构实现此目的。

with t1 as (select level id from dual where 1 = 0 connect by level <= 3),
     t2 as (select level id from dual where 1 = 1 connect by level <= 5)
select distinct * 
  from t1 
  where exists (select null from t2 where id = t1.id)
    or (select count(1) from t2) = 0
union all
select distinct * from t2 where (select count(1) from t1) = 0

t1t2模拟了一些数据。如果select中没有数据,则首先t2生成交集或从第一个表获取所有不同的行。 如果select中没有行,则union allt2之后)将从t1获取所有数据。

编辑:您可以更简单:

select * from t1 
intersect 
select * from t2 
union 
select * from t1 where (select count(1) from t2) = 0
union 
select * from t2 where (select count(1) from t1) = 0