steveh7 steveh7 - 1 year ago 73
MySQL Question

Create a matrix/table from a LEFT JOIN in SQL

I'd like to know a good solution for converting a LEFT JOIN into a table/matrix.

For example, given this schema:

id (integer)
name (string)

id (integer)
object_id (integer)
name (string)
value (string)

And these values:



I'd like to get this:

object_id | object_name | colour | shape | material

1 | ball | red | sphere | rubber
2 | box | brown | cube | NULL

Ideally this would be with an unknown number of attributes for each object, and be for MySQL without using stored procedures.

Answer Source

The thing with RDBMSs is that their purpose is to store and present what you already have. Creating columns dynamically was never intended.

This is a case that should be handled on the client that is to present the data.

With disregard to how RDBMSs are supposed to be used, you still won't find an easy way to do this. Especially not if you want the column list to be dynamic. You can build a dynamic SQL query and execute that, but there's no way to write a standard SQL query and get that result (since you always specify all columns explicitly, bar using *, but that can't be used to your advantage in this case.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download