ehmicky
ehmicky

Reputation: 2046

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

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:

What's the best practice?

Upvotes: 0

Views: 2234

Answers (1)

RichJ
RichJ

Reputation: 46

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.

Upvotes: 3

Related Questions