我想将项目关联到数据库中的城市、州或国家。但是,我希望“项目”表中只有一个字段来链接到与其关联的城市、州或国家(而不是三个条目“city_id”、“state_id”和'country_id')。看图片:
我知道在两者之间放置表格有一个技巧,但我搜索并仍然没有找到那种模式。
非常感谢!
Ĵ
我想将项目关联到数据库中的城市、州或国家。但是,我希望“项目”表中只有一个字段来链接到与其关联的城市、州或国家(而不是三个条目“city_id”、“state_id”和'country_id')。看图片:
我知道在两者之间放置表格有一个技巧,但我搜索并仍然没有找到那种模式。
非常感谢!
Ĵ
正如您所说,您可以使用中间表:
CREATE TABLE regions (
region_id INT NOT NULL AUTO_INCREMENT,
country_id INT NOT NULL,
state_id INT,
city_id INT,
PRIMARY KEY (region_id),
UNIQUE KEY (country_id, state_id, city_id)
CONSTRAINT FOREIGN KEY (country_id) REFERENCES countries (id),
CONSTRAINT FOREIGN KEY (country_id, state_id) REFERENCES states (country_id, id),
CONSTRAINT FOREIGN KEY ( state_id, city_id) REFERENCES cities ( state_id, id)
)
您需要regions
使用每个可能的(国家、州、城市)组合来更新此表,包括州或城市所在的位置NULL
。
您是否考虑过添加第五张表:place
. 每个country
,state
是city
一个place
. 每个item
都与一个place
.
这仍然没有标准化。您必须确保place
三个表中的值集是不相交的。item
在加入适当的表时,您还有更多工作要做。(本质上,您将一组困难换成另一组。)
Here's another idea, tell me what you think.
Since the fields in "item" will be optional, and that the relations between countries, states & cities is already defined, maybe I could try that way:
The primary keys of the countries, states & cities will be a unique ID through all those three tables (ex.: no state ID will have the same primary key as any city or country entry).
Then I could put this unique ID in the "items" table as well as the "type" which would give the table where to look for it ('cities', 'states', 'countries').
Since there could be some changes (ex.: 'regions', 'continents', etc.), then maybe it would be better to simply "add" a new table and type instead of regenerating the associative table.
Does it make sense?
Thanks!