将MySQL列值从查询转到行

时间:2018-07-07 21:28:09

标签: mysql sql database

我有以下查询:

mysql> select id_sucursal from dw_sucursallookup where sucursal = "Centro" 
           UNION ALL 
       select id_sexo from dw_sexolookup where sexo = "Hombre" 
           UNION ALL 
       select id_tiempo from dw_tiempolookup where fecha = "2018-06-27" and hora = "noche" 
           UNION ALL 
       select id_edad from dw_edadlookup where edad = "41-55" 
           UNION ALL 
       select id_tipo_comida from dw_tipo_comidalookup where tipo_de_comida = 'dulce';

具有以下输出:

+-------------+
| id_sucursal |
+-------------+
|  2014820869 |
|  2127812561 |
|  2020742459 |
|    49527792 |
|    95944605 |
+-------------+

我想要实现的是将结果转置为此:

+-------------+-------------+-------------+-------------+----------------+
| id_sucursal |   id_sexo   |  id_tiempo  |   id_edad   | id_tipo_comida |
+-------------+-------------+-------------+-------------+----------------+
|  2014820869 |  2127812561 |  2020742459 |    49527792 |       95944605 |
+-------------+-------------+-------------+-------------+----------------+

如何在mysql中做到这一点?我尝试搜索并找到了一些解决方案,但是没有一个能像我想要的那样工作。

预先感谢

1 个答案:

答案 0 :(得分:1)

您可以将select用于标量子查询:

select (select id_sucursal from dw_sucursallookup where sucursal = 'Centro') as id_sucursal,
       (select id_sexo from dw_sexolookup where sexo = 'Hombre') as id_sexo, 
       (select id_tiempo from dw_tiempolookup where fecha = '2018-06-27' and hora = 'noche') as id_tiempo
       (select id_edad from dw_edadlookup where edad = '41-55') as id_edad,
       (select id_tipo_comida from dw_tipo_comidalookup where tipo_de_comida = 'dulce') as tipo_de_comida