Introduction to databases
In this lesson, we introduce the student to the concept of one-to-many relationship
between tables of a database. We explain the concept, follow that up with an example,
and then conclude with a DIY exercise.
One-to-Many relationship
A database can consist of multiple tables that are related to each other. One of the
relationships that can exist between tables is a One-to-Many relationship. This means
one row in a primary table can be mapped to many rows in the secondary table. The
two tables are then connected through a foreign key. Let us take an example to clarify
further the 1-to-1 relationship.
Example
Say we have a student who is doing many modules. The attributes of the student can
be name and id. A module has an id, name, and code.
From this scenario we can generate two tables, one representing the basic information
of the student (StudentsTBL) and the other keeping information about the module
(ModulesTBL).
StudentsTBL
Field Description Data Type Constraints
ID The student number INTEGER Primary key.
Name Student name. VARCHAR Not null. Maximum size of 20.
ModulesTBL
Field Description Data Type Constraints
ID Unique qualification id. Primary key.
Name Qualification name. INTEGER Primary key
Code Qualification code VARCHAR Not null. Maximum size of 20.
Student_ID The field that links a INTEGER Foreign key.
student to a qualification.
The student id is appearing in both tables. The same foreign key can appear many
times in the secondary table because of the 1-to-Many relationship. The relationship
can be represented nicely in a schema as follows:
1
Student
Qualification
id
id
name
name
code
student_id
The above schema communicates the message that says 1 student is doing many
modules.
The symbol depicts a primary key.
The symbol depicts a foreign key.
We can then write Java code that will allow us to perform CRUD operations on the
tables generated. Please go through Tutorial 14 for an implementation of a similar
problem.
DIY
Do the exercise given in Tutorial 14.
Conclusion
In this chapter, we managed to introduce the student to the 1-to-many relationship.
This relationship simply says 1 row in one table maps to many rows in another table.
Thank you very much for having taken time to go through the lesson. Enjoy the rest of
the day and God bless you.