MySQL将表y中的2列连接到表x的行中

时间:2016-05-10 17:46:46

标签: mysql join unpivot

尝试围绕如何编写此SQL查询。

表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的行。非常感谢 - 这看起来应该很容易,我已经谷歌搜索了几个小时,但我可能没有使用正确的术语来解决我在搜索中所做的事情。 / p>

谢谢!

2 个答案:

答案 0 :(得分:1)

Uee union

 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'

答案 1 :(得分: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

顺便说一下,使用union时,其他数据库要求您为所有列提供相同的数据类型。这适用于mysql