doumaqing6652 2015-04-27 13:45
浏览 15
已采纳

我应该如何存储只有几个可能值的实体?

How should i store data like users's gender, religion, political views which is selecting from a list of 2-8 max values like 'male', 'female' or 'orthodox', 'muslim','judaism','catholic' etc? Also this values is constant, even admin cannot change 'female' to something else. In a Database it looks wierd to store a similar tables with only this 2-8 values and make JOIN with a parent table on foreign key. Second way - special object inside program code - but it's always bad to mix program logic with a data.

  • 写回答

2条回答 默认 最新

  • douyao1994 2015-04-27 14:25
    关注

    Whether or not something is looking "weird" depends on personal preferences or design structures. However, it is entirely logical to store anything in a database that has to do with, well, data. Even a given set of options can change in the distant or not so distant future. I can't count the times a client asked me to change a set of options a day, a week, or even a few years after having ensured me that the set wouldn't change, ever.

    Storing a list of options in a separate table is part of a relational database design. Relational database designs make it easy to get a set of data which includes or even excludes the options in any way in my opinion.

    I'd recommend doing it the good, old fashioned way, for example:

    1. Table user (id, user_name)
    2. Table option (id, option_label)
    3. Table user_option (id, user_id, option_id)

    A user that is both male and catholic would have a relation with two options:

    Table user          Table option           Table user_option
    +----+-----------+  +----+--------------+  +----+---------+-----------+
    | id | user_name |  | id | option_label |  | id | user_id | option_id |
    +----+-----------+  +----+--------------+  +----+---------+-----------+
    |  1 | john      |  |  1 | male         |  |  1 |       1 |         1 |
    |  2 | melody    |  |  2 | female       |  |  2 |       1 |         6 |
    |  3 | gerald    |  |  3 | orthodox     |  +----+---------+-----------+
    +----+-----------+  |  4 | muslim       |
                        |  5 | judaism      |
                        |  6 | catholic     |
                        +----+--------------+
    

    Showing all selected options per user can be done with the following query:

    SELECT `u`.*, GROUP_CONCAT( `o`.`option_label` SEPARATOR ', ' ) AS `options`
    FROM `user` AS `u`
    LEFT JOIN `user_option` AS `uo` ON `uo`.`user_id` = `u`.`id`
    LEFT JOIN `option` AS `o` ON `uo`.`option_id` = `o`.`id`
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。
  • ¥20 CST怎么把天线放在座椅环境中并仿真