MySQL中的一对多关系

MySQL中的一对多关系

本文介绍了MySQL中的一对多关系-如何建立模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个桌子:

1)区域2)地图

每个区域应至少具有1个地图,但也可以具有多个地图.

Each Area shall have at least 1 Map, but can also have more than one Map.

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

One Map can only belong to one Area.

如何在MySQL中构建它?

How to build this in MySQL?

推荐答案

在映射中添加引用区域主键的外键.这将在地图"和区域"之间建立一对多关系.

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.

关于在每个区域至少执行一张地图(如果有必要),这篇文章中有一些想法在这里.一种更简单的解决方案是创建一个仅显示具有地图区域的视图:

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;

这样,您可以创建一个区域,然后向其添加地图.您还可以将地图中的外键强制为NOT NULL,因此地图必须始终具有一个区域.

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.

这篇关于MySQL中的一对多关系-如何建立模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 04:05