简体   繁体   English

MySQL中的一对多关系 - 如何构建模型?

[英]One-to-Many relationship in MySQL - how to build model?

I have got two tables: 我有两张桌子:

1) Area 2) Map 1)区域2)地图

Each Area shall have at least 1 Map, but can also have more than one Map. 每个区域至少应有一个地图,但也可以有多个地图。

One Map can only belong to one Area. 一张地图只能属于一个区域。

How to build this in MySQL? 如何在MySQL中构建这个?

create table Area(id int primary key auto_increment, name varchar(100));

create table Map(id int primary key auto_increment, 
                 area_id int not null,
                 name varchar(100),
                 foreign key (area_id) references area(id));

SqlFiddle SqlFiddle

Each Map MUST have an Area , as area_id is not null (and is a Foreign key on Area ) 每个Map必须有一个Area ,因为area_id不为null(并且是Area上的Foreign key

But you won't be able (and it's not desired) to have "at least one map" for each area. 但是你不能(并且不希望)每个区域都有“至少一张地图”。

One day, you'll have to create an Area . 有一天,你必须创建一个Area And it won't have any Map at this time. 此时它不会有任何Map Or make "regular" checks to see the Areas without any Map. 或者进行“常规”检查以查看没有任何地图的区域。

You may want to delete an Area , if it has no more related Map , when you delete a Map . 您可能需要删除的Area ,如果没有更多的相关Map ,当你删除一个Map

Add a Foreign key in Map that references the Area's Primary Key. 在Map中添加引用Area的主键的外键。 That will enforce a one-to-many relationship between Maps and Areas. 这将强制地图和区域之间的一对多关系。

As for enforcing a minimum of one map per area (if that is necessary) there are some ideas in this post here . 至于强制最小单位面积的一个地图(如果必要)有在这篇文章中的一些想法在这里 One of the simpler solutions would be to create a view that only displays areas which have maps: 其中一个更简单的解决方案是创建一个只显示包含地图的区域的视图:

CREATE VIEW viewAreas AS
SELECT * 
FROM Areas, Maps
WHERE Areas.ID = Maps.AreaID;

This way, you can create an area, and then add maps to it. 这样,您可以创建一个区域,然后向其添加地图。 You can also enforce the Foreign Key in maps to be NOT NULL, so a map must always have an area. 您还可以将映射中的外键强制为NOT NULL,因此映射必须始终具有区域。

Map和Area各有一个表,Map上的外键链接到Area。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM