简体   繁体   中英

Merge column of two tables without relationship

I need to merge columns of two tables with different rows. It should put NULL value into table with less rows.

Example :

Assume these two simple tables :

table_one

+----+-----------+---------------------+
| id | title     | date                |
+----+-----------+---------------------+
| 10 | Good      | 2014-10-08 05:13:00 |
| 11 | NotBad    | 2014-10-24 00:00:00 |
| 12 | Excellent | 2014-10-26 14:00:00 |
| 13 | Bad       | 2014-10-11 19:31:23 |
+----+-----------+---------------------+

table_two

+----+------+
| id | name |
+----+------+
|  1 | Sara |
|  2 | Alex |
+----+------+

What output I need :

+----+-----------+---------------------+------+------+
| id | title     | date                |  id  | name |
+----+-----------+---------------------+------+------+
| 10 | Good      | 2014-10-08 05:13:00 |   1  | Sara |
| 11 | NotBad    | 2014-10-24 00:00:00 |   2  | Alex |
| 12 | Excellent | 2014-10-26 14:00:00 | NULL | NULL |
| 13 | Bad       | 2014-10-11 19:31:23 | NULL | NULL |
+----+-----------+---------------------+----+------+

What I've tried so far :

SELECT table_one.*, table_two.* FROM table_one, table_two

But that's not my desire! It will return Cartesian Product

PS :

These two tables has not any relationship between each other.

If you assume the first table has more rows, you can do this by generating a key using variables:

select t1.*, t2.*
from (select t1i.*, (@rn1 := @rn1 + 1) as rn
      from table_one t1i cross join (select @rn1 := 0) vars
     ) t1 left join
     (select t2i.*, (@rn2 := @rn2 + 1) as rn
      from table_two t2i cross join (select @rn2 := 0) vars
     ) t2
     on t1.rn = t2.rn;

You will have two surplus columns called rn , if you don't need that, list your columns instead of select t1.*, t2.* .

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