1

There are tables people, people_has_book and books. I want all people in my list but not everybody has a book, so I use a LEFT JOIN to link people to people_has_book, but linking people_has_book to books should not be a LEFT JOIN.

How would I do this?

Erwin Brandstetter
  • 539,169
  • 125
  • 977
  • 1,137
DeniseMeander
  • 746
  • 2
  • 7
  • 24

1 Answers1

3

You can use parentheses to prioritize joins. Like:

SELECT *
FROM   people p
LEFT   JOIN ( people_has_book pb JOIN books b USING (book_id) ) USING (people_id);

This is subtly different from two LEFT JOINs:

SELECT *
FROM   people p
LEFT   JOIN people_has_book pb USING (people_id)
LEFT   JOIN books b USING (book_id);

The latter would show rows from people_has_book even if there is no related entry in books. However, in a classic many-to-many implementation with FK constraints enforcing referential integrity, there is typically no effective difference for your particular query, since all people_has_book.book_id must reference an existing row in books anyway - with the exotic exception of NULL values. (If (people_id, book_id) is the PK of people_has_book, both columns are NOT NULL automatically.)

Related:

Erwin Brandstetter
  • 539,169
  • 125
  • 977
  • 1,137