2016-05-10 51 views
0

試圖圍繞如何編寫此SQL查詢來思考。MySQL將表2中的2列添加到表x的行中

表X有3列:YearIDValue,看起來像這樣

Year | ID |  Value 
2013  101  10000 
2014  101  11000 
2015  101  12000 
2013  102  7000 
2014  102  8000 
2015  102  9000 

而數據表Y有3列:IDCurr_Year_ValNext_Year_Val看起來像這樣

ID | Curr_Year_Val | Next_Year_Val 
101  13000     14000 
102  6000     5000 

我想編寫一個select語句將這兩個表連接在一起,但保持表X的佈局,如下所示:

Year   | ID | Value 
2013    101   10000 
2014    101   11000 
2015    101   12000 
Curr_Year_Val  101   13000 
Next_Year_Val  101   14000 

有沒有辦法達到這個結果?我已經想出瞭如何進行左連接來將表y中的列添加到表x中,但是希望將表y中的列未轉移到表x的行中。非常感謝 - 這似乎應該是這麼簡單,我一直在Google上搜索幾個小時,但我可能沒有使用我正在嘗試執行的搜索的正確術語。

謝謝!

回答

1

聽起來像是你應該使用union all

select year, id, value from x 
union all 
select 'curr_year_val', id, curr_year_val from y 
union all 
select 'next_year_val', id, next_year_val from y 
order by 2, 1 

BTW,其他數據庫就需要你有相同的數據類型所有列使用union時。這雖然與mysql

+0

謝謝!我在腦海中讓事情變得複雜得多。 – sqlnewb

1

UEE工會

select year, id, value 
from tableX 
where id ='101' 
union 
select 'curr_year_val', id, curr_year_val 
from tableY 
where id ='101' 
union 
select 'next_year_val', id, next_year_val 
from tableY 
where id ='101'