steveh7 steveh7 - 2 months ago 15
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:


objects
id (integer)
name (string)

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


And these values:


1,ball
2,box

1,1,colour,red
2,1,shape,sphere
3,1,material,rubber
4,2,colour,brown
5,2,shape,cube


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

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.)

Comments