Table 1 : User_Profile
-------------------------------------------------------------------------------------------
User_profile_id | Profile_form_id | Email | Zipcode | Firstname | Lastname
-------------------------------------------------------------------------------------------
1 | 4 |john@gmail.com | 123456 | john | peter
------------------------------------------------------------------------------------------
–
Table 2 : Profile_attribute_form
-------------------------------------------------------------------
profile_attribute_id | Profile_attribute_name | profile_form_id
-------------------------------------------------------------------
1 | Address | 4
-------------------------------------------------------------------
2 | Phone Number | 4
------------------------------------------------------------------
3 | City | 4
-------------------------------------------------------------------
Table 3 : User_Profile_attribute
User_profile_id | Profile_attribute_id | profile_attribute_value
--------------------------------------------------------------------------
1 | 1 | 23,Times road
--------------------------------------------------------------------------
1 | 2 | 9786530874
--------------------------------------------------------------------------
1 | 3 | New York
--------------------------------------------------------------------------
Needed Final Result :
-------------------------------------------------------------------------------------------
User_profile_id|Profile_form_id|Email |Zipcode|Firstname|Lastname|Address|PhoneNumber|City
-------------------------------------------------------------------------------------------
1 |4 |gm.com|123456 |john |peter |addr1 |9786530874 |NewY
-------------------------------------------------------------------------------------------
How to i build the mysql query for the above result.
You are need to do is
JOINthe tables and thenPIVOTthe data. However MySQL does not have aPIVOTfunction but you can replicate the functionality using an aggregate function and aCASEstatement.If you know the values to turn into columns then you can use the following:
see SQL Fiddle with Demo
Now if you want to perform this dynamically, meaning you do not know ahead of time the columns to transpose, then you should review the following article:
Dynamic pivot tables (transform rows to columns)
Your code would look like this:
see SQL Fiddle with Demo