我必须在两个select语句之间执行INTERSECTION
。只有当两个select语句都返回一些结果集时,才会发生交叉条件。如果任何一个返回O行,则Intersection不起作用,最终结果必须是返回某些行的语句。这可能在SQL
中(我不需要pl/sql
中的答案)吗?
答案 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
t1
和t2
模拟了一些数据。如果select
中没有数据,则首先t2
生成交集或从第一个表获取所有不同的行。
如果select
中没有行,则union all
(t2
之后)将从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