Relate Tables Instead of Repeating Data · practice
Follow a Loan to Its Member
A loan row identifies Riley as member 17, but a useful report should show MB-017 and Riley, not make its reader look up that ID by hand.
Open report.sql. Its current query starts from loans and shows member_id. We need one row from members for each loan. These are the values that line up:
loans.member_id | members.id | members.member_code | members.name |
|---|---|---|---|
17 | 17 | MB-017 | Riley |
Add this line after FROM loans:
INNER JOIN members ON members.id = loans.member_id
An inner join keeps rows whose ON comparison finds a match on both sides. The comparison uses the relationship you already declared. It does not compare the loan’s own ID or the item ID.
Then replace loans.member_id in the selected columns with:
members.member_code,
members.name AS member_name,
The table names qualify each column, making its source explicit. The alias gives the second name a useful result heading. Keep loans.id AS loan_id, the two date columns, and ORDER BY loans.id.
Press Run. The report.sql section should begin:
loan_id | member_code | member_name | checked_out_on | returned_on
501 | MB-017 | Riley | 2026-08-18 | NULL
All three visible loans have matching members, so all three remain in this inner-join report. Submit uses IDs that do not happen to resemble one another and gives two members the same displayed name. That makes the relationship, rather than a lucky number or name, decide the result.
This query has one clear path: start with a loan, match its member_id to members.id, and select the member facts from that matched row. Now you can follow the loan’s other relationship too.
Task
Edit report.sql so each loan follows loans.member_id to members.id with an INNER JOIN. Return loan_id, member_code, member_name, checked_out_on, and returned_on, ordered by loan ID.