Build a CRUD App with SQLAlchemy - Relationships & Joins

Relational databases map relationships

Between tables:
A driver has many vehicles.

Between rows across tables:
Driver Amy has 2 vehicles: a 2018 Nissan and a 2017 Ninja.


请添加图片描述

A foreign key is stored on what is known as the child table, which retrieves the primary key in the parent table, mapping a relationship from parent to child.
The foreign key is always stored in the child table and we say that a child object belongs to a parent objects through the foreign key that’s stored on the child table.


SELECT make, model, year FROM vehicles
	JOIN drivers
	ON vehicles.driver_id = drivers.id
	WHERE drivers.name = 'Sarah';

Parent table: drivers

Child table: vehicles

Primary key (on parent): drivers.id

Foreign key (on child): vehicles.driver_id


An INNER join selects all rows from both tables that have a match between the columns.

By default, in SQL, specifying the keyword JOIN (with no prefix) refers to a/an INNER JOIN.

猜你喜欢

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