在 union all sql 中合并结果

Merge results in union all sql

Table答:

Column1 | Column2
tableA01 | tableA11
tableA02 | tableA22

Table乙:

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,所以两者是等价的。

不过,更一般地说,您似乎想要交错这些值。您可以使用 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;

只需订购您的统一结果。

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