I'm making a preferences module for a system so users can define their own preferences for certain parts (stuff like lay-out, color-scheme, homescreen etc.). Every preference in the table has got a default value (in case the user hasn't defined one yet) and once the user has changed their preferences the system should use that user-defined value.
I'm having trouble with selecting the desired value, my query works with the user-defined value, but sadly it returns null
when the user hasn't defined a preference yet.
I have 2 tables
table **preferences**:
id
name
default_value
table **preferences_defined**:
id
preference_id
user_id
defined_value
I want to create a function to easily select the desired value by giving the user_id of the person to whom the preference applies and the name of the preference. At the moment my query looks like this:
SELECT IF(ISNULL(defined_value),default_value,defined_value) AS result
FROM preferences
LEFT JOIN preferences_defined ON preferences_defined.id = preferences.id
WHERE user_id = 17
AND name = "menu_items"
I guess the WHERE user_id = 17
part is where things go wrong because when there is no defined value available it means there also isn't a column named user_id.
I need to find a way to make this work.
So, I need to select the defined value if it exist (given the user_id
and the name
of the preference), if not, it will have to return the default value.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…