MySQL 将 table y 中的 2 列连接到 table x 的行中
MySQL Join 2 columns from table y into rows of table x
我正在思考如何编写此 SQL 查询。
Table X 有 3 列:Year
、ID
、Value
看起来像这样
Year | ID | Value
2013 101 10000
2014 101 11000
2015 101 12000
2013 102 7000
2014 102 8000
2015 102 9000
并且 table Y 有 3 列:ID
、Curr_Year_Val
、Next_Year_Val
看起来像这样
ID | Curr_Year_Val | Next_Year_Val
101 13000 14000
102 6000 5000
我想写一个 select 语句将这两个 table 连接在一起,但保持 Table X 的布局,如下所示:
Year | ID | Value
2013 101 10000
2014 101 11000
2015 101 12000
Curr_Year_Val 101 13000
Next_Year_Val 101 14000
有没有办法实现这个结果?我已经想出如何只进行左连接以将 table y 中的列添加到 table x,但宁愿将 table y 中的列取消透视到 table×。提前致谢 - 这看起来应该很简单,我已经谷歌搜索了几个小时,但我可能没有使用正确的术语来描述我在搜索中尝试做的事情。
谢谢!
UE联盟
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'
听起来你应该使用 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
.
我正在思考如何编写此 SQL 查询。
Table X 有 3 列:Year
、ID
、Value
看起来像这样
Year | ID | Value
2013 101 10000
2014 101 11000
2015 101 12000
2013 102 7000
2014 102 8000
2015 102 9000
并且 table Y 有 3 列:ID
、Curr_Year_Val
、Next_Year_Val
看起来像这样
ID | Curr_Year_Val | Next_Year_Val
101 13000 14000
102 6000 5000
我想写一个 select 语句将这两个 table 连接在一起,但保持 Table X 的布局,如下所示:
Year | ID | Value
2013 101 10000
2014 101 11000
2015 101 12000
Curr_Year_Val 101 13000
Next_Year_Val 101 14000
有没有办法实现这个结果?我已经想出如何只进行左连接以将 table y 中的列添加到 table x,但宁愿将 table y 中的列取消透视到 table×。提前致谢 - 这看起来应该很简单,我已经谷歌搜索了几个小时,但我可能没有使用正确的术语来描述我在搜索中尝试做的事情。
谢谢!
UE联盟
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'
听起来你应该使用 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
.