简体   繁体   中英

Merge two tables sql

This is my data set: Dataset 1:

col2 col3 col4
1      2    3
1      5    6

Dataset 2:

name2  name3 name4
 a       b     c
 d       e     l

I want to merge these two table like this:

col2 col3 col4 name2 name3 name4
 1    2     3   a     b     c
 1    5     6   d     e     l

I've tried with:

select * from table1 join table2 on true;

but gives me:

col2 col3 col4 name2 name3 name4
1     2    3     a    b      c
1     2    3     d    e      l

Which isn't correct. How could i achieve this?

Your result should have been four records.

You need a common key to join on, but don't have one. Here is one method:

select t1.col2, t1.col3, t1.col4, t2.name2, t2.name3, t2.name4
from (select t1.*, row_number() over () as seqnum
      from table1 t1
     ) t1 join
     (select t2.*, row_number() over () as seqnum
      from table2 t2
     ) t2
     on t1.seqnum = t2.seqnum;

Note that the ordering of the rows (defining the matching) is indeterminate. If this is important, then include order by clauses in the row_number() with the appropriate ordering.

据我所知,这应该工作:

SELECT * FROM table1 JOIN table2 ON table1.row_number()=table2.row_number();

在这种情况下,您不需要加入。您只需从两个表中进行选择即可。从table1,table2中选择*。

You don't need JOIN in this case if you want, you can get all columns like this (Because if the same number of columns in both tables):

SELECT col2,col3,col4 FROM dataset1
UNION
SELECT name2,name3,name4 FROM dataset2

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