Sub topic 9
Joining books, authors, and readings
Assume you know basic SELECT statements and that the schema from earlier chapters exists. The important tables here are books, authors, book_authors, and readings. A book can have several authors, and a book can have several reading entries over time.
Understand the relationships
The bookauthors table connects books and authors. It prevents repeating author columns such as author1 and author_2 in the books table. The readings table connects a book to a status, dates, and an optional rating.
A join combines related rows by matching column values.
| Join | Use | Effect |
|---|---|---|
| INNER JOIN | Require a matching row | Omits books without the related row |
| LEFT JOIN | Keep every row from the left table | Shows unmatched columns as NULL |
The schema uses bookid as the matching key between books and readings. The join table uses bookid and author_id to reach each author.
Build a result across four tables
This query lists every book, its authors, and its reading entries:
SELECT b.book_id,
b.title,
string_agg(a.name, ', ' ORDER BY ba.author_position) AS authors,
r.status,
r.started_on,
r.finished_on,
r.rating
FROM books AS b
LEFT JOIN book_authors AS ba USING (book_id)
LEFT JOIN authors AS a USING (author_id)
LEFT JOIN readings AS r USING (book_id)
GROUP BY b.book_id,
b.title,
r.reading_id,
r.status,
r.started_on,
r.finished_on,
r.rating
ORDER BY b.title, r.started_on;The first LEFT JOIN finds author links for each book. The second finds the author rows. The third finds reading entries. A book with no author or reading entry still appears because the query starts with books and uses left joins.
string_agg combines several author rows into one comma-separated value. Without it, a book with three authors would produce three result rows. The GROUP BY columns preserve one result row for each reading entry. If a book has two reading entries, it appears twice, with the same author list.
To show only books that have finished readings, use INNER JOIN for readings and add a filter:
SELECT b.title,
string_agg(a.name, ', ' ORDER BY ba.author_position) AS authors,
r.finished_on,
r.rating
FROM readings AS r
JOIN books AS b USING (book_id)
JOIN book_authors AS ba USING (book_id)
JOIN authors AS a USING (author_id)
WHERE r.status = 'finished'
GROUP BY r.reading_id, b.book_id, b.title, r.finished_on, r.rating
ORDER BY r.finished_on;Here, every returned row has a matching book, author, and finished reading. The reading_id in GROUP BY prevents separate reading entries for the same book from being merged.
Exercise
Exercise
Which join type should you use when you want a report containing books that have no reading entry yet?
Show answer
Use a LEFT JOIN from books to readings, so books without a matching reading remain in the result with NULL reading columns.