2016-12-09 50 views
2

我有一個像如下─結合2個表不具有任何關係

表1的情侶對錶:

A B C D <<Columns 
1 2 3 4 <<single row 

表2:

W X Y Z << Columns 
5 6 7 8 << Single row 

我想結合這兩張表,它會給我以下結果

結果:

P Q R S << Column headers 
1 2 3 4 << row from table1 
5 6 7 8 << row from table2 

預期的結果將有列標題,如P,Q,R,S,並從表1行並從表2

行如何實現這個使用SQL?

回答

1
  • UNION ALL將不會消除重複
  • 在集合操作(​​UNION/INTERSECT/EXCEPT)中,別名從第一個查詢中獲取(目前我只知道一個異常 - Hive r equires別名是相同的所有查詢 - 我認爲這是一個bug)

select A as P, B as Q, C as R, D as S 
from table1 

union all 

select W,X,Y,Z 
from table2 

+---+---+---+---+ 
| p | q | r | s | 
+---+---+---+---+ 
| 1 | 2 | 3 | 4 | 
| 5 | 6 | 7 | 8 | 
+---+---+---+---+ 

表2與3列

select B as Q, C as R, D as S 
from table1 

union all 

select X,Y,Z 
from table2 

+---+---+---+ 
| q | r | s | 
+---+---+---+ 
| 2 | 3 | 4 | 
| 6 | 7 | 8 | 
+---+---+---+ 

select A as P, B as Q, C as R, D as S 
from table1 

union all 

select null,X,Y,Z 
from table2 

+--------+---+---+---+ 
| p | q | r | s | 
+--------+---+---+---+ 
| 1  | 2 | 3 | 4 | 
| (null) | 6 | 7 | 8 | 
+--------+---+---+---+ 
+0

當Table2只有3列時會發生什麼 - X,Y,Z?我是否也應該在這種情況下使用UNION ALL? – Sagar

+0

查看編輯答案 –

+0

感謝您的快速回復。 – Sagar

1

_Updated更嚴格,更完整,感謝@AntDC(和@馬特)和@Dudu Markovitz__

使用UNION用別名,就像這樣:

SELECT A AS P, B AS Q, C AS R, D AS S 
FROM table1 
UNION 
-- or UNION ALL if you want to keep duplicate rows 
SELECT W, X, Y, Z 
FROM table2 
+2

我想你只需要別名第一選擇列。 另外 - 如果行是相同的,您將需要UNION ALL。 – AntDC

+0

@AntDC我不同意:它會保留第二個select的原始col名稱,所以不會給出預期的結果。 – cFreed

+1

@AntDC'建議在MySQL中工作http://rextester.com/TMCWM42152,sql server http://rextester.com/LIQDCM48260,PostrgeSQL http://rextester.com/DZZF66752很確定它在Oracle中工作,通常每個平臺。即使你留下別名,發現OP沒有聲明刪除重複的行,所以我也同意你可能需要'UNION ALL' – Matt