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. ie 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
It's a good idea to do this. This is not even denormalization; the resulting table is still normalized (ie no redundance etc.).
What you want is an aggregated row per person:
select
person_id,
max(case when fk_attribute_id = 1 then attribute_value end) as person_name,
max(case when fk_attribute_id = 2 then attribute_value end) as person_age,
...
from person_data
group by person_id;
Of course you need to know all attributes to build this query.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.