Jump to content

Slightly complex JOIN issue with COUNT


wpb

Recommended Posts

Hello,

 

I have two tables in my database, one called bookinfo and one called reviews.

 

There's a column in the reviews table that references books in the bookinfo table called book_id.

 

I want to query the bookinfo table for each book_id and also count the number of reviews for each book_id in the same query.

 

At the moment I have this:

 

SELECT bookinfo.title, COUNT(reviews.review_id) AS number_reviews FROM bookinfo LEFT JOIN reviews ON bookinfo.book_id = reviews.book_id GROUP BY reviews.book_id

 

This works, but doesn't return results for books with zero reviews (i.e. no entries in the reviews table). I was hoping that the LEFT JOIN would take care of that, but it doesn't seem to make any difference.

 

Does anyone have any suggestions about this?

 

Thanks,

 

Will

 

Link to comment
Share on other sites

Thanks - that works. Could you explain why?

 

Also, if I add in a condition, so I'm only counting say, official reviews, it doesn't work as I expect:

 

SELECT bookinfo.title, COUNT(reviews.review_id) AS number_reviews FROM bookinfo

LEFT JOIN reviews ON bookinfo.book_id = reviews.book_id WHERE reviews.official="Y" GROUP BY bookinfo.book_id

 

This knocks out books that don't have any official reviews, but I want it to return them, just with number_reviews=0.

 

Thanks,

 

Will

 

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.