繁体   English   中英

合并两个表sql

[英]Merge two tables sql

这是我的数据集:数据集1:

col2 col3 col4
1      2    3
1      5    6

数据集2:

name2  name3 name4
 a       b     c
 d       e     l

我想像这样合并这两个表:

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

我尝试过:

select * from table1 join table2 on true;

但是给我:

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

这是不正确的。 我怎样才能做到这一点?

您的结果应该是四个记录。

您需要一个公共密钥才能加入,但没有一个。 这是一种方法:

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;

请注意,行的顺序(定义匹配项)是不确定的。 如果这很重要,则在row_number()包括有适当顺序的order by子句。

据我所知,这应该工作:

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

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

在这种情况下,如果需要,则不需要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