mysql - 将 MySQL 列值从查询转换为行

标签 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 中做到这一点?我尝试搜索并找到了一些解决方案,但没有一个像我想要的那样工作。

提前致谢

最佳答案

您可以将 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

关于mysql - 将 MySQL 列值从查询转换为行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51227069/

相关文章:

c# - 如何上传图片 phpmyadmin ASP.Net

Mysql获取状态的最新行

mysql - 如何使用 JOIN 解决查询

mysql - View 更改有什么问题?

mysql - 我如何计算另一张 table 上的所有喜欢?

Mysql仅当id存在于另一个表中时才插入一行

mysql - 获取 2 个不同相关表中两个字段的总和

ruby-on-rails - 这个 Rails 文件存储在哪里?数据库/开发.sqlite3

java - 将java语言映射到数据库

Mysql,桥接表与字段?