簡體   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