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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17044792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 17:54:58  来源:igfitidea点击:

One-to-Many relationship in MySQL - how to build model?

mysqlrelational-database

提问by tellob

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.

每个区域至少有 1 张地图,但也可以有不止一张地图。

One Map can only belong to one Area.

一张地图只能属于一个区域。

How to build this in MySQL?

如何在 MySQL 中构建它?

采纳答案by Jenius

Add a Foreign key in Map that references the Area's Primary Key. That will enforce a one-to-many relationship between Maps and Areas.

在 Map 中添加一个引用区域主键的外键。这将强制地图和区域之间的一对多关系。

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,因此映射必须始终有一个区域。

回答by Rapha?l Althaus

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 MapMUST have an Area, as area_idis not null (and is a Foreign keyon Area)

每个Map必须有一个Area, asarea_id不是 null (并且是Foreign keyon Area

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. And it won't have any Mapat this time. Or make "regular" checks to see the Areas without any Map.

有一天,您将不得不创建一个Area. 而此时它不会有任何Map。或者进行“定期”检查以查看没有任何地图的区域。

You may want to delete an Area, if it has no more related Map, when you delete a Map.

您可能需要删除Area,如果没有更多的相关的Map,当你删除一个Map

回答by Jenius

A table each for Map and Area, with a foreign key on Map linking to Area.

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