← SQL and databases

Joining three tables

Follow two links in one query.

Start this lesson

A loan links a member and a book. To show the member's name and the book's title together, you join loans to members and loans to books: two JOINs, each with its own ON. In general, joining N tables needs N - 1 join conditions. Tables in the middle, like loans, order_items and grades, are the bridges.

SELECT m.name, b.title
FROM loans l
JOIN members m ON l.member_id = m.id
JOIN books b ON l.book_id = b.id;

Each loan row finds its member and its book. The result reads like "Ana Souza borrowed The Quiet Orchard".

Start from the bridge table and join outwards. It is the table that holds both pointers.