2016-09-18 107 views
0

這是我的數據集: 數據集1:合併兩個表的SQL

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 

這是不正確的。我怎麼能做到這一點?

回答

2

您的結果應該是四條記錄。

你需要一個共同的密鑰加入,但沒有一個。這裏有一種方法:

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條款,並具有適當的順序。

0

據我看到的,這應該工作:

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

這是行不通的。你不能在沒有'over()'的情況下使用窗口函數,並且你不能在這樣的連接條件下使用它們。 –

0

你不需要在這個case.You加入可以只從兩個tables.select *從表1,表2中進行選擇。

+0

不是,因爲我已經試過沒有成功,它給了我上面解釋的錯誤。 – xCloudx8

0

,如果你想你不需要JOIN在這種情況下,你可以得到這樣所有列(因爲如果兩個表中的列數相同):

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

我不能因爲他們是兩種不同的類型(整數和字符串) – xCloudx8