简体   繁体   English

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

[英]How to merge rows of two tables when there is no relation between the tables in sql

Suppose We have ten rows in each table A and table B table A with single 假设我们在每个表A有十行,而表B在表A有一行

ColA 
  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10

and table B with column 和表B

ColB 
  11 
  12 
  13 
  14 
  15 
  16 
  17 
  18 
  19 
  20

Output required: 需要输出:

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

PS : There is no relation between the two table. PS:两张桌子之间没有关系。 Both columns are independent. 两列都是独立的。 Also 1, 2...19, 20 , they are row id s and if considered the data only then in an unordered form. 同样是1,2 ... 19,20,它们是行id ,如果仅考虑数据,则以无序形式。

UPDATED In SQL Server and Oracle you can do it like this 更新在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 

Output: 输出:

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

Here is SQLFiddle demo (SQL Server) 这是SQLFiddle演示(SQL Server)
Here is SQLFiddle demo (Oracle) 这是SQLFiddle演示(Oracle)

In MySql you can do 在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

Here is SQLFiddle demo 这是SQLFiddle演示

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
select colA from tableA 
union 
select colB from tableB;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM