Imagine you're running a school cafeteria where students can choose their favorite juice boxes each day. Some students like to enjoy multiple juice boxes, but each juice box belongs to only one student. This scenario perfectly illustrates a one-to-many relationship in a database.
A one-to-many relationship means that one entity from one table can be associated with one or more entities in another table. In our cafeteria example:
Let’s explore this relationship through four approaches:
Each student in the school is assigned a unique ID and can select one or more juice boxes to accompany their snacks. Each juice box is identified by its own unique ID and is linked to the student who chose it.
Writing down examples of the data helps clarify the relationship. Here’s a small portion of the data:
students table:id name
1 Alim
2 Andrei
3 Belma
juice_boxes table:id juice date student_id
111 apple 2020-01-22 1
112 apple 2020-01-22 2
113 orange 2020-01-22 3
114 apple 2020-01-23 1
115 orange 2020-01-23 1
116 peach-mango 2020-01-23 2
117 grape 2020-01-23 3
In this data, you can see which student drank which juice on specific days. For example:
A schema describes how the database is structured. Here are the schemas for the students and juice_boxes tables:
students table schema:column type constraints
id INTEGER PRIMARY KEY
name TEXT
juice_boxes table schema:column type constraints
id INTEGER PRIMARY KEY
juice TEXT
date TEXT
student_id INTEGER FOREIGN KEY REFERENCES students(id)
The schema diagram visually represents the relationship:
students table contains one row per student.juice_boxes table contains multiple rows referencing the same student.To create these tables and establish the one-to-many relationship in SQLite3, use the following SQL:
CREATE TABLE students (
id INTEGER PRIMARY KEY,
name TEXT
);
CREATE TABLE juice_boxes (
id INTEGER PRIMARY KEY,
juice TEXT,
date TEXT,
student_id INTEGER,
FOREIGN KEY (student_id) REFERENCES students(id)
);
In this SQL:
student_id column in the juice_boxes table serves as a FOREIGN KEY.FOREIGN KEY references the id column in the students table, establishing the relationship.You’ve learned to identify and specify a one-to-many relationship in four ways:
FOREIGN KEY constraints.One-to-many relationships are common in many systems, including:
Understanding one-to-many relationships is crucial for designing efficient and logical databases. Practice creating these relationships in different scenarios to solidify your understanding.