如何在表中存储用户选择的多个选项
所以我希望我的用户能够限制谁可以联系他们。
他们应该能够过滤几个因素,包括年龄(例如必须在 18 - 29 岁之间)、收入(收入必须在 25,000 美元 - 60,000 美元之间)、他们正在寻找的东西(例如友谊、闲逛等),他们使用什么药物(大麻、冰毒、可卡因等)等。
问题是,我希望他们能够针对某些标准(例如药物)选择并存储多个选择,但是我不知道应该如何将其存储在数据库中,也不知道应该如何构建表以最好地实现这一点。
例如,我将如何存储在此上下文中为“药物”选择“大麻”、“可卡因”和“海洛因”的用户行?我是否可以将这些值简单地存储为“药物”列中的逗号分隔值?或者我应该以完全不同的方式来做?
执行此操作的最佳方法是什么(考虑到每次用户想要联系另一个用户时我显然都必须检索并检查此信息)以及为什么?
So I want my users to be able to restrict who may contact them.
There are several factors they should be able to filter, including Age (e.g. Must be between 18 - 29), income (must earn between $25,000 - $60,000), what they're looking for (e.g. Friendship, Hang out, etc.), what drugs they do (Marijuana, Meth, Cocaine, etc), etc.
The problem is, I want them to be able to select and store multiple choices for some of the criteria (e.g. drugs), but I do not know how I should store that in the DB or how I should structure the table to best accomplish that.
For example, how would I store a user's row that for "drugs" chose "Marijuana", "Cocaine", and "Heroin" within this context? Would I simply store those as comma-separated values in the "Drugs" column? Or should I do it in a completely different way?
What would be the best way to do this (considering I will obviously have to retrieve and check this information every time a user wants to contact another user) and why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,不要将值以 CSV 格式存储在数据库中。相反,创建一个名为
user_drug
的 连接表 并为每个用户存储一行/药物组合:No, don't store the values in CSV format in the database. Instead create a join table called
user_drug
and store one row for each user/drug combination:数据库列(至少理论上)不应包含多个值。不幸的是,有些程序员在单个列中存储多个值(例如用逗号分隔的值) - 这些程序员(在大多数情况下)破坏了 DB 和 SQL 的概念。
我建议您阅读数据库规范化来开始组织你的桌子。并且,尽最大努力实现Codd 的第三范式
A DB column (at least theorethically) should NOT hold multiple values. Unfortunately, there are some programmers that store multiple values in a single column (values separated by comma for examples) - those programmers (in most cases) destroy the concept of DB and SQL.
I suggest you to read about Database Normalization to get a start in organizing your tables. And, do your best to achieve the Codd's Third Normal Form
你可以尝试用这个:
You can try with this: