Imagine a classroom where students study multiple subjects, and each subject is attended by multiple students. This scenario perfectly demonstrates a many-to-many relationship in a database. By understanding and implementing this type of relationship, you can handle complex data connections efficiently.
A many-to-many relationship occurs when:
This relationship can be thought of as two one-to-many relationships that connect in both directions. To implement it in a database, you use a join table, which contains FOREIGN KEY references to the primary keys of the two related tables.
Let’s break it down into four components:
Consider students in a school. Each student studies multiple subjects, and each subject is attended by multiple students:
To connect the students and subjects tables, we use a join table called student_subject. This table stores the primary keys from both tables as foreign keys to establish the relationship.
students table:id name
1 Alim
2 Andrei
3 Belma
subjects table:id name
101 Reading
102 Writing
103 Arithmetic
104 Art
105 Music
student_subject join table:student_id subject_id
1 101
1 102
1 103
1 104
2 101
2 102
2 103
2 105
3 101
3 102
3 103
3 104
In this data, you can observe the many-to-many relationship:
The schema represents how the database tables are structured. Here are the schemas for the students, subjects, and student_subject tables:
students table schema:column type constraints
id INTEGER PRIMARY KEY
name TEXT
subjects table schema:column type constraints
id INTEGER PRIMARY KEY
name TEXT
student_subject join table schema:column type constraints
student_id INTEGER FOREIGN KEY REFERENCES students(id)
subject_id INTEGER FOREIGN KEY REFERENCES subjects(id)
The schema diagram visualizes this relationship:
student_subject table.To create these tables and establish the many-to-many relationship in SQLite3, use the following SQL:
CREATE TABLE students (
id INTEGER PRIMARY KEY,
name TEXT
);
CREATE TABLE subjects (
id INTEGER PRIMARY KEY,
name TEXT
);
CREATE TABLE student_subject (
student_id INTEGER,
subject_id INTEGER,
FOREIGN KEY (student_id) REFERENCES students(id),
FOREIGN KEY (subject_id) REFERENCES subjects(id)
);
Here, the student_subject table serves as the join table, linking students and subjects through their primary keys.
You’ve learned to identify and specify a many-to-many relationship in four ways:
Many-to-many relationships are common in various systems, including:
By mastering many-to-many relationships, you can design flexible and powerful databases capable of handling complex data structures.