在数据库表中存储多个 ID 的理想解决方案是什么?
我的房地产应用程序有一个数据库表,它保存用户的查询(查询)。该表保存有关特定房地产查询的所有信息。
数据库表看起来像这样:
CREATE TABLE IF NOT EXISTS `queries` (
`id` bigint(20) NOT NULL auto_increment,
`category_id` int(10) NOT NULL,
`serial` varchar(30) NOT NULL,
`minBudget` int(11) NOT NULL,
`maxBudget` int(11) NOT NULL,
`city_id` int(10) NOT NULL,
`area_id` int(10) NOT NULL,
`locality` varchar(100) NOT NULL,
`status` tinyint(1) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
在 city_id
和 area_id
中,我可能会在某些情况下想要存储多个 ID;例如,10、12、20、50 等。
我应该如何将其存储在数据库中?
我应该使用 varchar
数据类型并将其保存为定义了分隔符的字符串,然后获取数组中的值吗?
My real-estate application has a database table that it holds the queries(inquiries) by the user. This table holds all the information about a particular real-estate query.
The database table looks something like this:
CREATE TABLE IF NOT EXISTS `queries` (
`id` bigint(20) NOT NULL auto_increment,
`category_id` int(10) NOT NULL,
`serial` varchar(30) NOT NULL,
`minBudget` int(11) NOT NULL,
`maxBudget` int(11) NOT NULL,
`city_id` int(10) NOT NULL,
`area_id` int(10) NOT NULL,
`locality` varchar(100) NOT NULL,
`status` tinyint(1) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
In city_id
and area_id
chances are there are situations where I would want to store multiple IDs; for example, 10, 12, 20, 50 and so on.
How should I be storing this in the databsae?
Should I use the varchar
datatype and hold it as a string with a delimiter defined, then fetch the value in an array?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以这样做,但这并不是真正的首选解决方案。这是数据库规范化中的经典权衡。
“更正确”的方法是拥有表“城市”和“区域”,以及表“queries_cities”和“queries_areas”,它们是多对多关联的。
否则,如果城市或地区 ID 发生变化会发生什么?您不必编写一个脚本来手动检查和更新所有查询记录,而不是在一个地方更改单个记录。
You can do that, but it's not really the preferred solution. This is the classic tradeoff in database normalization.
The "more correct" approach is to have tables "cities" and "areas", and tables "queries_cities" and "queries_areas" that are many-to-many to relate them.
Else- what happens if a city or area id changes? Rather than change a single record in one place, you'll get to write a script to go through and update all the query records manually.
如果它们是另一个表的 ID,请勿使用 varchar。使用多对多表将它们映射在一起。
这比将内容填充到 varchar 中要干净得多 - 例如,它允许您说:
编辑:嗯,我很蹩脚,没有包含外键,但是您明白了。
Do NOT use a varchar if those are IDs to another table. Use a many-to-many table mapping them together.
This will be much cleaner than stuffing things into a varchar - for instance, it allows you to say:
Edit: meh, I'm lame and didn't include foreign keys, there, but you get the point.