How to query in such a way that values becomes columns? Having the table foo like:

| id | name |
|  1 | Foo1 |
|  2 | Foo2 |


And the table bar like:

| id | foo_id | key | value |
|  1 |      1 |   a | foo1a |
|  2 |      1 |   b | foo1b |
|  3 |      2 |   a | foo2a |
|  4 |      2 |   b | foo2b |


How can I mount my SQL in a way that produces an output like:

| id | name |   a   |   b   |
|  1 | foo1 | foo1a | foo1b |
|  2 | foo2 | foo2a | foo2b |


I have no idea even if it is possible.



On a high-level problem (maybe there is a better solution) I want to make the keys on a entity dynamic.
I think what you are looking for is called a Pivot.  I work primarily with Microsoft SQL Server, so I don't know all the inter-workings of this.

There appears to be a really well received Stack Overflow post that answers a similar question for MySQL.

https://stackoverflow.com/questions/7674786/mysql-pivot-table

Hopefully that give you what you are looking for.