将两个结果集合并为一个,其中一个可能为空

时间:2014-07-17 23:05:21

标签: sql

我想将两个结果集合在一起,但有一个或另一个结果集为空的情况。发生的事情是,如果其中一个结果集为空,则无法返回任何结果。我现在这样做的方式基于this SO question.所以基本上我的sql看起来像这样

Select * from (Select err.is,... FROM table1 err), (Select arr.id,... FROM table2)

有解决方法吗?

1 个答案:

答案 0 :(得分:0)

你可能想要union all而不是加入,所以也许这会做你想要的:

(Select err.is,... FROM table1 err)
union all
(Select arr.id,... FROM table2)

否则,如果你确实想要交叉连接,那么这样的事情可能会起作用:

with t1 as (
     Select err.is,... FROM table1 err
    ),
     t2 as (
     Select arr.id,... FROM table2
    )
select t1.*, t2.*
from t1 cross join t2
union all
select t1.*, t2.*
from t1 left outer join
     t2
     on 1 = 0
where not exists (select 1 from t2)
union all
select t1.*, t2.*
from t2 left outer join
     t1
     on 1 = 0
where not exists (select 1 from t1);