mandel
mandel

Reputation: 181

What's wrong with my sql query using left joins?

I'm using MySQL. I have 3 tables I'm trying to connect in a query and I can't see what I'm doing wrong with the following query:

Table 1: books (list of book information) Table 2: bookshelf (list of books a member owns) Table 3: book_reviews (list of book reviews)

I want to generate a list of all books a user has in their bookshelf, as well as any reviews they have made. The following query gives me a list only of books the user has reviewed; I want all of their books. I thought the second LEFT OUTER JOIN would do this - connecting the bookshelf titles to the book reviews titles, but I don't get any books with no reviews (there should be lots). Removing the second JOIN statement (and putting bookshelf in the FROM statement) allows me to get a list of titles with no reviews, but it shows all book reviews by all users.

SELECT books.title, book_reviews.comments
FROM books
LEFT OUTER JOIN book_reviews ON books.ID = book_reviews.book_id
LEFT OUTER JOIN bookshelf ON book_reviews.user_id = bookshelf.user_id
WHERE bookshelf.book_id = books.ID
AND bookshelf.user_id =1

I imagine I'm missing something very obvious, but I've been reading about joins and going over my logic and I'm blind to it. Thanks to anyone who can help me see...

Upvotes: 0

Views: 97

Answers (1)

a1ex07
a1ex07

Reputation: 37382

Try this:

SELECT books.title, book_reviews.comments
FROM bookshelf
LEFT OUTER JOIN books ON books.ID = bookshelf.book_id
LEFT OUTER JOIN book_reviews ON book_reviews.book_id = books.ID  
 AND book_reviews.user_id = bookshelf.user_id

WHERE bookshelf.user_id =1

Upvotes: 1

Related Questions