Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have got two tables:

1) Area 2) Map

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

One Map can only belong to one Area.

How to build this in MySQL?

like image 626
tellob Avatar asked Jun 11 '13 13:06

tellob


People also ask

How do you create a one-to-many relationship in MySQL?

Click on the appropriate tool for the type of relationship you wish to create. If you are creating a one-to-many relationship, first click the table that is on the “many” side of the relationship, then on the table containing the referenced key. This creates a column in the table on the many side of the relationship.

How do I create a one-to-many table in MySQL?

One to Many Relationship (1:M) This is where a row from one table can have multiple matching rows in another table this relationship is defined as a one to many relationship. This type of relationship can be created using Primary key-Foreign key relationship.

How do you create a one-to-many relationship in a database?

To implement a one-to-many relationship in the Teachers and Courses table, break the tables into two and link them using a foreign key. We have developed a relationship between the Teachers and the Courses table using a foreign key.


1 Answers

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

Each Map MUST have an Area, as area_id is not null (and is a Foreign key on 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 Map at this time. Or make "regular" checks to see the Areas without any Map.

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

like image 80
Raphaël Althaus Avatar answered Oct 14 '22 12:10

Raphaël Althaus