Relational databases are designed to handle complex relationships between data. Among the three types of relationships—one-to-one, one-to-many, and many-to-many—the many-to-many relationship is especially powerful for linking multiple entities in both directions. In this lesson, you’ll learn how to design, understand, and work with many-to-many relationships using join tables.
A many-to-many relationship occurs when:
To implement this relationship, we use a third table called a join table, which:
Let’s look at a real-world scenario where a many-to-many relationship is required. Consider an e-commerce platform:
The relationship is represented by three tables: products, orders, and a join table order_details.
products: Stores information about each product.orders: Stores information about customer orders.order_details: Acts as the join table, linking products and orders through their primary keys.
The order_details table contains the following foreign keys:
product_id: References the id in the products table.order_id: References the id in the orders table.Here’s an example of data from each table:
products table:id name
1597 Glass Coffee Mug
1598 Metallic Coffee Mug
1599 Smart Coffee Mug
users table:id name
1 Alice
2 Bob
orders table:id purchaser_id
10 1
11 1
12 2
order_details table:id order_id product_id
1 10 1599
2 11 1597
3 11 1598
4 12 1597
5 12 1598
6 12 1599
By using the order_details table, you can determine:
Here’s how to implement the schema in SQLite3:
CREATE TABLE products (
id INTEGER PRIMARY KEY,
name TEXT
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
purchaser_id INTEGER
);
CREATE TABLE order_details (
id INTEGER PRIMARY KEY,
order_id INTEGER,
product_id INTEGER,
FOREIGN KEY (order_id) REFERENCES orders(id),
FOREIGN KEY (product_id) REFERENCES products(id)
);
The order_details table serves as the join table, linking the products and orders tables.
To optimize the database structure, remember to apply normalization rules:
In this lesson, you’ve gained a solid understanding of:
Many-to-many relationships are used in various systems, including:
With this knowledge, you’re now equipped to design and work with many-to-many relationships in your database projects.