Ok, I’m still a beginner in sql and can not figure this one out yet.
I have four tables: companies, persons, details, person_details.
companies:
id, compname
(1, ACME),
(2, ACME Group), ...
persons:
id, name, lastname, company id
(1, donald, duck, 1),
(2, lucky, luke, 1),
(3, mickey, mouse, 2)
details:
id, description
(1, 'weight'),
(2, 'height'),
(3, 'haircolor'), ...
person_details:
id, persons id, details id, value
(1, 1, 1, 70),
(2, 1, 3, 'red'),
(3, 2, 1, 90),
(4, 3, 2, 180)
As you can see, not all persons have all the details and the list of available details is variable.
Now, for a given arary of person ids and detail ids, I would like to get rows containing: company name and id, person name and last name, detail name and value for each of the details in the supplied array.
Let’s say persons(1,2), details(1,3) should result in:
companies.id, companies.name, name, lastname, details.description, person_details.value,...
1, ACME, donald, duck, 'weight', 70, 'haircolor', 'red'
2, ACEM, lucky, luke, 'weight', 90, 'haircolor', null
Help, please…
Based on your description it seems like you want to pivot the data but unfortunately MySQL does not have a pivot function so you will need to replicate it using an aggregate function with a
CASEstatement.If you know the description values ahead of time you can hard-code your query to the following:
See SQL Fiddle with Demo
If you have an unknown number of values, then you can use a prepared statement to generate this dynamically similar to this:
See SQL Fiddle with Demo
Both versions generate the result: