Database relations
Databases are not intended for storing data but for storing relationships.
Relationships are what make Entities worthy.
Your main goal in designing databases is to identify Entities and Relationships between them.
I show here the types of Relationships and how to store them.
There are 3 types of relationships in Relational Databases:
1- One to one
2- One to many
3- Many to many
The type of relationships between two entities will define how we store them.
One to one example:
Imagine a school offering personal laptops to their students. If a laptop is assigned to only one student, and the student can only have one laptop assigned by the school, this is a one-to-one relationship.
One to many example:
Another school with different rules.
In this school, a laptop is assigned to only one student, but the student can get assigned more than one laptop (one PC and one Mac, for example). This relationship becomes one-to-many because one student can have many laptops, but each laptop is assigned to only one student.
Many to many example:
Another school yet, other rules.
This school has small groups of three laptops that only three students can use.
This relationship becomes many-to-many because one student can use many laptops, and many students can use each laptop.
How to store relationships?
Let me use these two entities as examples:
Students(Id (Primary Key), Name)
Computers(Id (Primary Key), SerialNumber)
1- One to one
The way to store this relationship type is by adding the key of one of the Entities into the other.
You can store this relationship in any of these ways:
Students(Id, Name, ComputerId)
Computers(Id (Primary Key), SerialNumber)
Or
Students(Id (Primary Key), Name)
Computers(Id, SerialNumber, StudentId)
2- One to many
The way to store this relationship type is by adding the key of Entities on the side One into the Entity of the side Many.
There is only one possible way.
Computers(Id, SerialNumber, StudentId)
3- Many to many
This type of relationship needs to create an extra table for storing it. You will name the table at your convenience using a meaningful name for the relation. The table must contain the key from each table.
AssignedComputers(StudentId, ComputerId)
You can also add extra data you want to consider for that relationship like the maximum number of hours to be used.
AssignedComputers(StudentId, ComputerId, MaxHoursToUse
Comments
Post a Comment