How to represent a many-to-many relationship in a relational database?

此生再无相见时 提交于 2019-12-13 20:45:47

问题


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:

  • Country has a Edition column that includes either null or the Edition that it belongs to. My problem with this: I have been taught nulls are evil in a database.
  • Edition has a Countries column that is an array of Country. My problem with this: I have been taught arrays are evil in a database.

What's the best practice?


回答1:


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.

Here is an example

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

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

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

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.



来源:https://stackoverflow.com/questions/24681249/how-to-represent-a-many-to-many-relationship-in-a-relational-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!