简体   繁体   English

在MySQL中枢转一张表格

[英]Pivot one table in MySQL

I'm currently running into a problem where I am required to pivot many rows into a single row, defined by a specific key. 我目前遇到一个问题,我需要将许多行旋转到由特定键定义的单行中。 I know the GROUP_CONCAT functionality and am using that currently, but I would like to avoid having to use explode in PHP after fetching my results. 我知道GROUP_CONCAT功能,目前正在使用,但是我想避免在获取结果后必须在PHP中使用explode。 My table looks like this: 我的桌子看起来像这样:

----------------------------------
| primary_id | key_value | value |
----------------------------------
| 1          | my_key_1  | val_1 |
| 1          | my_key_2  | val_2 |
| 1          | my_key_3  | val_3 |
| 2          | my_key_4  | val_4 |
| 2          | my_key_5  | val_5 |
----------------------------------

And I would like to build a MySQL-Query that presents this exactly like this for primary id 1 and primary id 2: 而且我想构建一个MySQL-Query,它对于主ID 1和主ID 2完全像这样显示:

-----------------------------------------------
| primary_id | my_key_1 | my_key_2 | my_key_3 |
-----------------------------------------------
| 1          | val_1    | val_2    | val_3    |
-----------------------------------------------

------------------------------------
| primary_id | my_key_4 | my_key_5 |
------------------------------------
| 2          | val_4    | val_5    |
------------------------------------

So I can retrieve the output as an array in PHP, with the form: 因此,我可以使用以下形式将输出作为PHP中的数组检索:

$output[1][my_key_1] = val_1
$output[1][my_key_2] = val_2
...

The GROUP_CONCAT functionality works, but it would be much nicer to just have the value in the form I needd it only using SQL. GROUP_CONCAT功能可以工作,但是仅使用SQL以我需要的形式获得值会更好。

Would appreciate any pointers, best regards. 将不胜感激,最好的问候。

Use a Pivot 使用枢轴

select max(case (when key_value=my_key_1 then val_1 end)), max(case (when key_value=my_key_2 then val_2 end)), from... etc... 从...等中选择max(case(当key_value = my_key_1然后val_1结束)),max(case(当key_value = my_key_2然后val_2结束)),...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM