tags:

views:

24

answers:

1

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...

+1  A: 

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
a1ex07
That's it. I presume by starting with books instead of bookshelf I must have been focusing on the wrong thing.
mandel