I'm no MySQL guru, but I get around the basic stuff pretty well. Thanks for your feedback.
I have two tables user
and favorite
. Each user can have multiple unique favorites.
table user u
[ user_id + name ]
100 | Sally
table favorite fav
[ fav_id + user_id + fav_key + fav_val ]
1 | 100 | icecream | mint
2 | 100 | candybar | snickers
3 | 100 | color | red
I want to create a SELECT
statement that will turn the user's favorites into columns using the fav_key
value as the column header. *The problem is I will never know what the fav_val
value will be as these are user entered, so the column names have to be generated dynamically.
SELECT ...
[ user_id + name + fav_icecream + fav_candybar + fav_color ]
100 | Sally | mint | snickers | red
With some distant thought of performance in mind -- one of the issues is that I don't want to run two SELECT
statements to get the user data and the user favorites (plus I like the idea of having the columns dynamically named in this way).
UPDATE
So this is called, pivoting, excellent.
What if I don't ever know what the values are? I need to dynamically generate the columns from a query on favorites.