I´m trying to denormalize some data in a table, but I cannot do it because I do not find the way to do it right way in mysql.
Table:person_attribute
Attribute_ID Attribute
------------ ---------
1 Person Name
2 Person Age
3 Person Gender
.
.
.
34 Phone Number
34 attributes as if now, but it is subject to change. i.e i may get additional attributes also.
Table:person_data
Person ID fk_Attribute_ID Attribute_Value
--------- --------------- -------------
1 1 Max
1 2 55
1 3 male
2 1 John
2 2 20
2 3 male
Excepted Output:
Person ID Person Name Person Age Person Gender
--------- ----------- ---------- -------------
1 Max 55 male
2 john 20 male
My solution:
Select
Person ID,
case when fk_Attribute_ID = ( select Attribute_ID from person_attribute where Attribute_ID = 1) then Attribute_Value end as Person Name,case when fk_Attribute_ID = ( select Attribute_ID from person_attribute where Attribute_ID = 2) then Attribute_Value end as Person Age,case when fk_Attribute_ID = ( select Attribute_ID from person_attribute where Attribute_ID = 3) then Attribute_Value end as Person Gender From person_attribute left join on person_data (Attribute_ID = fk_Attribute_ID)
Person ID Person Name Person Age Person Gender
--------- ----------- ---------- -------------
1 Max null null
1 null 55 null
1 null null male
2 john null null
2 null 20 null
2 null null male
Please help me with excepted output. Thanks