mysql - 合并所有 sql 中的结果

标签 mysql sql union

表 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/

相关文章:

Python - 无法连接到数据库

带有面向对象 PHP 的 PHP 购物车

MySQL计数没有count函数?

sql - Oracle SQL 在哪里过滤多行

sql - 如何从表中选择列的唯一值?

MySQL 生成出现在多个列中的名称列表,按字母顺序分组

graph - 对两个图运行 sparql 查询?

mysql - 组合 While 循环生成的结果集

mysql - SQL 查询和结果

sql - 左外连接查询极慢 - SQL Server