获取全部联合的输出,而无需使用全部联合



我得到了一种情况,可以在不使用union的情况下找到 2 个表之间的公共记录。我能做到。但我不能做"工会所有人"。我的意思是我必须在不使用union all的情况下找出 2 个表的输出,包括重复表。有没有办法做?

table A has x column and values 1,2,3 
and
table B has x column and values 3,4,5
select x from A union select x from B;
o/p 1,2,3,4,5
select x from A union all select x from B;
o/p should be 1,2,3,3,4,5,6(not necessarily in order)

Union输出我可以通过以下查询实现

select nvl(a.x,b.x) output from A full outer join B on A.x=b.X order by output;

但是如果不使用oracle内置union all,我就无法union all

你离你的答案太近了。

对于union,您使用了以下查询,其中在 x 列上有一个连接:

select nvl(a.x,b.x) output from A full outer join B on A.x=b.X order by output;

对于union all,您可以使用永远无法满足的连接条件。它将生成与union all相同的输出。

因此,您必须使用以下查询:

select nvl(a.x,b.x) output from A full outer join B on 1=2 order by output;

干杯!!

如果你提到一些边缘情况,你可能会在面试中获得加分,这里可能是:

主键

如果其中一个表中的列不是主键(或 leadt 唯一(,则建议的解决方案UNION

select nvl(a.x,b.x) output from A full outer join B on A.x=b.X

失败,您必须使用DISTINCT

select distinct  nvl(a.x,b.x) output from A full outer join B on A.x=b.X 

可为空的列

如果其中一个表中的列可为空,则建议的解决方案为UNION ALL

select nvl(a.x, b.x) x from a full join b on a.x is null or b.x is null

失败on 1=2的另一种解决方案工作正常。

我必须找出 2 个表的输出,包括不使用的重复项union all

select nvl(a.x, b.x) x from a full join b on a.x is null or b.x is null

德布提琴

最新更新