Learn with Abdou

Chapter 7 · Concept 5 of 6

Follow a loan through its keys

three-table joins, and which branch is which

A loan names a member, a tool and a staff member by their keys, and each of those has a branch of its own.

Can you

  • Start from the table the report is about and follow each foreign key to its parent
  • Refuse a join on a shared column that is not a relationship
  • Choose which of three branches a question is really about

Follow a loan through its keys

SELECT l.id AS loan_id, m.first_name AS member_first_name, t.name AS tool_name
FROM loans l
JOIN members m ON m.id = l.member_id
JOIN tools t ON t.id = l.tool_id
WHERE l.id <= 5
ORDER BY l.id;
Five loans, each with the member who borrowed and the tool that left. Open in the playground

A loan row names a member, a tool and a staff member by their keys. When each output row should describe a loan, start from loans and follow each foreign key to its parent: JOIN members on l.member_id, JOIN tools on l.tool_id, JOIN staff on l.staff_id. Three joins, one row per loan, 120 rows. The hub is the table whose rows the report is about.

Resist the shortcut. Members and tools both carry a branch_id, so you could pair them on it. That pairs every member with every tool at the same branch, 341 rows that mean nothing: a shared branch is not a loan. For every join you write, name the fact that makes the pair real.

The Tool Library has three different branches in one loan: the branch that owns the tool, the home branch of the member, and the branch where the staff member works. They are three relationships, three joins to the branches table under three aliases. The director's replacement-value report attributes value to the branch that owns the tool. Pick the branch the question is about, not the one that is easiest to reach.

Rule of thumb. Start from the table the report is about and follow each foreign key to its parent.

The ladder

Six rungs

Start at the first rung even if the idea looks familiar: it is answerable from the reading alone, and the climb is where the difficulty lives. A wrong answer sends you back to the paragraph that teaches it, then to a hint, then to the worked answer.

Learn

  1. Level 1: Watch it answered

    1 exercise · Not yet

    Practise this rung
  2. Level 2: Fill the blank

    1 exercise · Not yet

    Practise this rung

Practise

  1. Level 3: Predict the result

    1 exercise · Not yet

    Practise this rung
  2. Level 4: Write it yourself

    1 exercise · Not yet

    Practise this rung

Master

  1. Level 5: Repair it

    1 exercise · Not yet

    Practise this rung
  2. Level 6: Transfer it

    1 exercise · Not yet

    Practise this rung

Keep practising

The whole bank for this concept, in any order, with the same review, hint and worked answer.

Practice here is evidence for you and your instructor, never a grade. Grades live in Canvas.