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. 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:
-----------------------------------------------
| 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:
$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.
Would appreciate any pointers, best regards.