简体   繁体   English

合并结果合并所有SQL

[英]Merge results in union all sql

Table A: 表A:

Column1 | Column2
tableA01 | tableA11
tableA02 | tableA22

Table B: 表B:

Column1 | Column2
tableB01 | tableB11
tableB02 | tableB22

When sql using union all in these tables, the results like this: 当sql在这些表中使用union all时,结果如下:

SQL SQL

SELECT * FROM tableA UNION ALL SELECT * FROM tableB

Result 结果

Column1  | Column2
tableA01 | tableA11
tableA02 | tableA22
tableB01 | tableB11
tableB02 | tableB22

I ask: It possible merge the results? 请问:是否可以合并结果?

I want the results somelike this: 我想要这样的结果:

Column1  | Column2
tableA01 | tableA11
tableB01 | tableB11
tableA02 | tableA22    
tableB02 | tableB22

Thanks! 谢谢!

Your result sets are the same, because result sets are unordered , unless you have an order by . 您的结果集是相同的,因为结果集是无序的 ,除非您的order by Because your sample query doesn't have an order by , the two are equivalent. 因为您的示例查询没有order byorder by ,所以两者是等效的。

More generally, though, you seem to want to interleave the values. 不过,更笼统地说,您似乎希望对值进行交织。 You can do this using order by by doing: 您可以通过以下操作使用order by执行此操作:

select ab.*
from ((select a.*, (@rna := @rna + 1) as rn, 1 as which
       from a cross join (select @rna := 0) params
       order by <something>  -- You should order by something here so the ordering is well defined
      ) union all
      (select b.*, (@rnb := @rnb + 1) as rn, 2 as which
       from b cross join (select @rnb := 0) params
       order by <something>  -- You should order by something here so the ordering is well defined
      )
     ) ab
order by rn, which;

Simply order your unified results. 只需订购统一结果即可。

SELECT *
FROM (
    SELECT Column1, Column2 FROM tableA
    UNION ALL 
    SELECT Column1, Column2 FROM tableB
) Results 
ORDER BY Column1, Column2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM