[英]What is the ideal solution for storing multiple ID's in a database table?
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; 在
city_id
和area_id
中,有些情况下我想存储多个 ID。 for example, 10, 12, 20, 50 and so on. 例如10、12、20、50等。
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? 我应该使用
varchar
数据类型并将其作为定义了定界符的字符串保存,然后在数组中获取值吗?
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. “更正确”的方法是使表“ cities”和“ areas”以及表“ queries_cities”和“ queries_areas”之间具有多对多关系。
Else- what happens if a city or area id changes? 否则,如果城市或地区ID发生变化会怎样? 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.
无需在一个地方更改单个记录,而是可以编写一个脚本来手动更新和更新所有查询记录。
Do NOT use a varchar if those are IDs to another table. 如果这些字符是另一个表的ID,请不要使用varchar。 Use a many-to-many table mapping them together.
使用多对多表将它们映射在一起。
CREATE TABLE IF NOT EXIST `query_cities` (
`id` bigint(20) NOT NULL auto_increment,
`query_id` bigint(20),
`city_id` bigint(20)
)
CREATE TABLE IF NOT EXIST `query_areas` (
`id` bigint(20) NOT NULL auto_increment,
`area_id` bigint(20)
)
This will be much cleaner than stuffing things into a varchar - for instance, it allows you to say: 这比将东西塞进varchar更加干净-例如,它允许您说:
SELECT c.city_name, c.state, c.whatever FROM queries q
JOIN cities c ON (q.city_id = c.id) WHERE q.id = ?
Edit: meh, I'm lame and didn't include foreign keys, there, but you get the point. 编辑:嗯,我很me脚,那里没有外键,但是您明白了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.