mysql if row doesn't exist, grab default value

后端 未结 2 1876
旧巷少年郎
旧巷少年郎 2020-12-20 06:05

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 preferen

相关标签:
2条回答
  • 2020-12-20 06:42

    WHERE (user_id = 17 OR user_id IS NULL) AND name = "menu_items"

    And just to clean up the rest of the query:

    The id in preferences defined doesn't need to be there, use a combined key of preference_id and user_id instead.

    If the id of preferences was named preference_id, the long ON statement could be replaced with USING(preference_id)

    The IF function can be replaced with COALESCE(defined_value, default_value)

    0 讨论(0)
  • 2020-12-20 06:47

    If I where you I would do one/two queries.

    So you would get:

    $query = "SELECT * FROM preferences_defined WHERE user_id = 17 AND name = 'menu_items'"
    

    And then in PHP:

    $rows = mysql_num_rows($query);
    if($rows == 0){
    $query = "SELECT * FROM preferences WHERE name = 'menu_items'"}
    

    This way your right query will always be in the $query var. Hope this helps!

    0 讨论(0)
提交回复
热议问题