表 A:
Column1 | Column2
tableA01 | tableA11
tableA02 | tableA22
表 B:
Column1 | Column2
tableB01 | tableB11
tableB02 | tableB22
当sql在这些表中使用union all
时,结果如下:
SQL
SELECT * FROM tableA UNION ALL SELECT * FROM tableB
结果
Column1 | Column2
tableA01 | tableA11
tableA02 | tableA22
tableB01 | tableB11
tableB02 | tableB22
请问:是否可以合并结果?
我想要这样的结果:
Column1 | Column2
tableA01 | tableA11
tableB01 | tableB11
tableA02 | tableA22
tableB02 | tableB22
谢谢!
最佳答案
您的结果集是相同的,因为结果集无序,除非您有排序方式
。因为您的示例查询没有 order by
,所以两者是等价的。
不过,更一般地说,您似乎想要交错这些值。您可以通过以下方式使用 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;
关于mysql - 合并所有 sql 中的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34019565/