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.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值