表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
谢谢!
答案 0 :(得分:1)
您的结果集是相同的,因为结果集无序,除非您有order by
。由于您的示例查询没有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;
答案 1 :(得分:1)
只需订购统一的结果。
SELECT *
FROM (
SELECT Column1, Column2 FROM tableA
UNION ALL
SELECT Column1, Column2 FROM tableB
) Results
ORDER BY Column1, Column2