Assume I have two tables related with one to many:
Person:
- name
- age
- phone
Attributes:
- fk
- field
- value
for example
Person:
id | name | age | phone |
---|---|---|---|
1 | John | 18 | null |
2 | Sue | 22 | 1234567890 |
3 | Linda | 31 | 9876543210 |
Attributes:
id | fk | field | value |
---|---|---|---|
1 | 1 | hair | brown |
2 | 1 | eyes | blue |
3 | 2 | hair | black |
4 | 3 | height | 6 |
Is it possible to create a query with a result that looks like this:
name | age | phone | hair | eyes | height |
---|---|---|---|---|---|
John | 18 | null |
brown | blue | null |
Sue | 22 | 1234567890 | black | null |
null |
Linda | 31 | 9876543210 | null |
null |
6 |
2
Answers
Unfortunately MySQL doesn’t support
pivot
as far as I am aware, but if this does not need to have a dynamic amount of attributes, you could self joinAttributes
vialeft join
, and filter the joins to the attributes needed:If you do require a dynamic number of attributes, you can create a prepared statement, but I don’t have an example of that readily available.
Here’s a solution using
conditional aggregation
.View on DB Fiddle