I have a table used by one piece of 3rd party software (say user_fields) that has for each row a user_id, a field_id and a field_value. Crappy I know.
I also have another user table of my own, users, that contains the values needed to populate this, except the field_id which is "magic" and corresponds to the custom field mapping.
How can I write a select query that will turn this:
user_id | company_name | first_name | country
---------------------------------------------------
1 | Nutty Choc Company | Si | GB
2 | Ljubljanske R Us | Pie | IT
Into this?
user_id | field_value | field_id
---------------------------------------
1 | Nutty Choc Company | 10
1 | Si | 11
1 | GB | 12
2 | Ljubljanske R Us | 10
2 | Pie | 11
2 | IT | 12
I'm using Postgresql 8.4, and intend the query to be fed to insert.
I had a stab at it by using unnest and an array, to expand the fields into rows, but it unnests after processing any other field in the select, and so just duplicates the value for the unnested rows.
Any ideas?
Cheers, Si
EDIT: formatting and clarification that dodgy name-value table is 3rd party.