Build a CRUD App with SQLAlchemy - One-to-Many Relationship

There are 3 types of relationships in relational database design:

  1. One-to-One
  2. One-to-Many (or Many-to-One)
  3. Many-to-Many

One-to-One
A row in table A can have only one matching row in table B, and vice versa.

This is not a common relationship type, as the data stored in table B could just have easily been stored in table A. However, there are some valid reasons for using this relationship type. A one-to-one relationship can be used for security purposes, to divide a large table, and various other specific purposes.

Example:
An account has one user.
A passport belongs to a person.
(passport stores foreign key person_id)


One-to-Many (or Many-to-One)
This is the most common relationship type. In this type of relationship, a row in table A can have many matching rows in table B, but a row in table B can have only one matching row in table A.

One-to-Many relationships can also be viewed as Many-to-One relationships, depending on which way you look at it.

Example:
An owner has many properties.
(properties stores foreign key owner_id)

A teacher has many students.


Many-to-Many
In a many-to-many relationship, a row in table A can have many matching rows in table B, and vice versa.

A many-to-many relationship could be thought of as two one-to-many relationships, linked by an intermediary table.

The intermediary table is typically referred to as a “junction table” (also as a “cross-reference table”). This table is used to link the other two tables together. It does this by having two fields that reference the primary key of each of the other two tables.

Example:
A school teaches many subjects, and a subject is taught in many schools.

An order has many order_items, and the order_items has many products.

CREATE TABLE order_items(
	order_id REFERENCES orders(id)
	product_id REFERENCES products(id)
	quantity INTEGER
	PRIMARY KEY (product_id, order_id)
);

In many-to-many, a special association table exists to join the two tables together, storing two foreign keys that link to the two foreign tables that have a relationship with each other.

猜你喜欢

转载自blog.csdn.net/BSCHN123/article/details/121695969