当sql中的表之间没有关系时,如何合并两个表的行

时间:2013-08-29 07:03:26

标签: mysql sql sql-server oracle

假设每个表A和表B中有十行 表A单

ColA 
  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10

和表B

ColB 
  11 
  12 
  13 
  14 
  15 
  16 
  17 
  18 
  19 
  20

需要输出:

SingleColumn
   1 
  11 
   2 
  12 
   3 
  13 
   4 
  14 
   5 
  15 
   6 
  16 
   7 
  17 
   8 
  18 
   9 
  19 
  10 
  20

P.S:两张桌子之间没有关系。两列都是独立的。同样是1,2 ... 19,20,它们是行id,如果只考虑数据,则以无序形式。

3 个答案:

答案 0 :(得分:2)

更新在SQL Server和Oracle中,您可以这样做

SELECT col
  FROM
(
  SELECT a.*
    FROM
  ( 
    SELECT cola col, 1 source, ROW_NUMBER() OVER (ORDER BY cola) rnum
      FROM tablea
  ) a 
  UNION ALL 
  SELECT b.*
    FROM
  (
    SELECT colb col, 2 source, ROW_NUMBER() OVER (ORDER BY colb) rnum
      FROM tableb
  ) b
) c
 ORDER BY rnum, source 

输出:

| COL |
|-----|
|   1 |
|  11 |
|   2 |
|  12 |
|   3 |
|  13 |
|   4 |
|  14 |
|   5 |
|  15 |
|   6 |
|  16 |
|   7 |
|  17 |
|   8 |
|  18 |
|   9 |
|  19 |
|  10 |
|  20 |

这是 SQLFiddle 演示(SQL Server)
这是 SQLFiddle 演示(Oracle)

在MySql中你可以做到

SELECT col
  FROM
( 
  (
    SELECT cola col, 1 source, @n := @n + 1 rnum
      FROM tablea CROSS JOIN (SELECT @n := 0) i
     ORDER BY cola
   )
  UNION ALL
  (
    SELECT colb col, 2 source, @m := @m + 1 rnum
      FROM tableb CROSS JOIN (SELECT @m := 0) i
     ORDER BY colb
   )
) c
 ORDER BY rnum, source

这是 SQLFiddle 演示

答案 1 :(得分:1)

SELECT col FROM (
  select colA as col
        ,row_number() over (order by colA) as order1
        ,1 as order2
  from tableA
  union all
  select colB
        ,row_number() over (order by colB)
        ,2
  from tableB
) order by order1, order2

答案 2 :(得分:0)

select colA from tableA 
union 
select colB from tableB;