您要实现的这个过程称为unpivot。不幸的是,MySQL 没有任何 UNPIVOT 函数,但您可以使用 UNION ALL 查询来获取结果。
UNION ALL 将多列转换为多行。您可以对每个表执行此操作,然后在fecha
,hora
和列名上加入表。查询将类似于以下内容:
select x.col,
x.price_x,
y.price_y
from
(
select id, fecha, hora, 'hfmachine1' col, hfmachine1 price_x
from prices_x
union all
select id, fecha, hora, 'hcmachinex' col, hcmachinex price_x
from prices_x
union all
select id, fecha, hora, 'hfmachiney' col, hfmachiney price_x
from prices_x
union all
select id, fecha, hora, 'hfmachinez' col, hfmachinez price_x
from prices_x
union all
select id, fecha, hora, 'hfmachinep' col, hfmachinep price_x
from prices_x
) x
left join
(
select id, fecha, hora, 'hfmachine1' col, hfmachine1 price_y
from prices_y
union all
select id, fecha, hora, 'hcmachinex' col, hcmachinex price_y
from prices_y
union all
select id, fecha, hora, 'hfmachiney' col, hfmachiney price_y
from prices_y
union all
select id, fecha, hora, 'hfmachinez' col, hfmachinez price_y
from prices_y
union all
select id, fecha, hora, 'hfmachinep' col, hfmachinep price_y
from prices_y
) y
on x.fecha = y.fecha
and x.hora = y.hora
and x.col = y.col;
看演示
如果可能的话,我的建议是考虑对表格进行规范化,这将使查询数据变得更加容易。