Oracle SQL - UNION ALL语句的替代方法

时间:2014-03-20 11:37:33

标签: sql oracle oracle11g oracle10g

给定使用union的follownig查询,

Select col1,col2,col3,col4,col5,cast(multiset(temp.col1 from table(cast(xslt.children as clob_nt)) temp, col6
from tableA
union all
Select a,b,c,d,e,cast(multiset(temp.col1 from table(cast(tableB.children as clob_nt)) temp, col7
from tableB

我希望得到以下输出(即两个表中的行)

tableA.x tableA.x tableA.x tableA.x tableA.x tableA.clob(x) tableA.x
tableA.x tableA.x tableA.x tableA.x tableA.x tableA.clob(x) tableA.x
tableB.x tableA.x tableA.x tableB.x tableB.x tableB.clob(x) tableB.x
tableB.x tableA.x tableA.x tableB.x tableB.x tableB.clob(x) tableB.x
tableB.x tableA.x tableA.x tableB.x tableB.x tableB.clob(x) tableB.x

还有哪些其他选项可以让我在不使用' union'的情况下运行查询或者'联合所有'并得到相同的结果

2 个答案:

答案 0 :(得分:1)

您实际上可以在Oracle中执行此操作,但编码有点混乱。我们的想法是在非匹配字段上执行full outer join,然后使用coalesce()将结果合并在一起:

select coalesce(a.col1, b.a) as col1,
       coalesce(a.col2, b.b) as col2,
       coalesce(a.col3, b.c) as col3,
       coalesce(a.col4, b.d) as col4,
       coalesce(a.col5, b.e) as col5,
       coalesce(cast(multiset(temp.col1 from table(cast(xslt.children as clob_nt)),
                cast(multiset(temp.col1 from table(cast(b.children as clob_nt))
               ) as temp,
       coalesce(a.col6, b.col7) as col6
from tableA a full outer join
     tableB b
     on 0 = 1;

但是,我不确定前面的内容是否适用于temp列。一个原因是cast()似乎没有完全公式化:

答案 1 :(得分:1)

您可以将每个查询的结果存储在(临时)结果表中,然后最后一次获取所有结果。

我能想到这样做的唯一原因是将工作分成更小的块来节省资源(不确定它会产生多大的差别)或者分别对不同的查询进行基准测试。

下面在Oracle中看起来或多或少。 (我更像是MSSQL人员)

CREATE GLOBAL TEMPORARY TABLE MyWorkingTable
   ON COMMIT PRESERVE ROWS 
   AS Select col1,col2,col3,col4,col5,cast(multiset(temp.col1 from table(cast(xslt.children as clob_nt)) temp, col6
      from tableA
     WHERE 1 = 2

INSERT MyWorkingTable (col1,col2,col3,col4,col5, temp, col6)
Select col1,col2,col3,col4,col5,cast(multiset(temp.col1 from table(cast(xslt.children as clob_nt)) temp, col6
      from tableA;


INSERT MyWorkingTable (col1,col2,col3,col4,col5, temp, col6)
Select col1,col2,col3,col4,col5,cast(multiset(temp.col1 from table(cast(xslt.children as clob_nt)) temp, col6
      from tableB;

INSERT MyWorkingTable (col1,col2,col3,col4,col5, temp, col6)
Select col1,col2,col3,col4,col5,cast(multiset(temp.col1 from table(cast(xslt.children as clob_nt)) temp, col6
      from tableC;


-- etc

SELECT * FROM MyWorkingTable;