dongse5408 2011-02-12 12:04
浏览 473
已采纳

mysql如果行不存在,则获取默认值

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.

  • 写回答

2条回答 默认 最新

  • duanjiao5082 2011-02-12 12:46
    关注

    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)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题