如何在关系数据库中表示多对多关系? [英] How to represent a many-to-many relationship in a relational database?

查看:413
本文介绍了如何在关系数据库中表示多对多关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个表Country和Region.一个地区是一个或多个国家/地区的集合.有些国家/地区不在任何地区.

I have two tables Country and Region. A Region is a set of one or several Countries. Some Countries are in no Region.

我应该如何在关系数据库中表示它?我想到了以下两种可能性:

How should I represent this in a relational database? I thought of the two following possibilities:

  • 国家/地区具有一个Edition列,其中包含null或它所属的Edition.我的问题是:有人告诉我,数据库中的null是有害的.
  • 版本具有国家/地区"列,该列是国家/地区的数组.我的问题是:我被告知数组在数据库中是邪恶的.

什么是最佳做法?

推荐答案

一种方法是创建包含两列的第三个表,一个包含CountryID,另一个包含RegionID,其中分别是Country和Region的唯一标识符.

One way is to create a third table with two columns, one contains CountryID the other RegionID where these are respectively the unique identifiers of Country and Region.

此表中的行表示一个国家和一个地区之间的关系.由于表中可以有多行,因此可以存储多对多关系.如果没有关系(某些国家/地区不在某个地区),则表中没有行.

A row in this table means a relationship between a Country and a Region. As you can have more than one row in the table, you can store many-to-many relationships. If there is no relationship ( some countries are in no region ), there is no row in the table.

这是一个例子

表1-国家
ID名称
1西班牙
2法国
3德国
4挪威
5贝尔吉姆

Table 1 - Country
ID Name
1 Spain
2 France
3 Germany
4 Norway
5 Belguim

表2-区域
ID名称
1欧洲
2 BeneLux
3欧盟贸易区
4亚洲

Table 2 - Region
ID Name
1 Europe
2 BeneLux
3 EU Trading Region
4 ASIA

表3-CountryRegion
国家地区
1 1
2 1
3 1
4 1
5 1
1 3
2 3
3 3
5 2

Table 3 - CountryRegion
Country Region
1 1
2 1
3 1
4 1
5 1
1 3
2 3
3 3
5 2

表达了以下内容-
西班牙在欧洲(国家1,地区1)
法国在欧洲
德国在欧洲
挪威在欧洲
比利时在欧洲
西班牙在欧盟
法国在欧盟
德国在欧盟
贝尔吉姆(Belguim)在BeneLux中

Which has expressed the following -
Spain is in Europe ( Country 1, Region 1 )
France is in Europe
Germany is in Europe
Norway is in Europe
Belgium is in Europe
Spain is in EU
France is in EU
Germany is in EU
Belguim is in BeneLux

亚洲没有国家

No countries are in ASIA

在地理上可能并不完整或正确,但我希望它能显示出原理.

Ths may not be geographically complete, or correct but I hope it shows the principle.

这篇关于如何在关系数据库中表示多对多关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆