简体   繁体   中英

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

ColA 
  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10

and table B with column

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. 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.

UPDATED In SQL Server and Oracle you can do it like this

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)
Here is SQLFiddle demo (Oracle)

In MySql you can do

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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