合并两个表 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
我想像这样合并这两个 table:
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();
你不需要加入这个 case.You 可以只 select 来自 tables.select * 来自 table1,table2.
在这种情况下,如果需要,您不需要 JOIN
,您可以像这样获取所有列(因为如果两个表中的列数相同):
SELECT col2,col3,col4 FROM dataset1
UNION
SELECT name2,name3,name4 FROM dataset2
这是我的数据集: 数据集 1:
col2 col3 col4
1 2 3
1 5 6
数据集 2:
name2 name3 name4
a b c
d e l
我想像这样合并这两个 table:
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();
你不需要加入这个 case.You 可以只 select 来自 tables.select * 来自 table1,table2.
在这种情况下,如果需要,您不需要 JOIN
,您可以像这样获取所有列(因为如果两个表中的列数相同):
SELECT col2,col3,col4 FROM dataset1
UNION
SELECT name2,name3,name4 FROM dataset2