简体   繁体   English

合并两个表sql

[英]Merge two tables sql

This is my data set: Dataset 1: 这是我的数据集:数据集1:

col2 col3 col4
1      2    3
1      5    6

Dataset 2: 数据集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. 如果这很重要,则在row_number()包括有适当顺序的order by子句。

据我所知,这应该工作:

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): 在这种情况下,如果需要,则不需要JOIN ,就可以像这样获得所有列(因为如果两个表中的列数相同):

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

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

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