Nyxynyx
Nyxynyx

Reputation: 63619

Sort products by number of reviews

I have a mysql database with

I want to retrieve results for 'product_id' = 123, but sort if by number of reviews. I am able to find the number of reviews for a particular product using COUNT('review_id'), but how do I sort the results by number of reviews?

Upvotes: 1

Views: 428

Answers (4)

Bjoern
Bjoern

Reputation: 16304

If you want the products with the most reviews first...

SELECT P.product_id, 
       IFNULL(COUNT(R.product_ID),0) as "Reviews"
FROM product as P
LEFT JOIN review as R ON P.product_ID = R.product_id
GROUP BY P.product_id
ORDER BY Review DESC;

...otherwise switch DESC with ASC.

Upvotes: 1

Craig
Craig

Reputation: 991

To save doing the count twice use: count('review_id') as num_reviews and then order by num_reviews

Upvotes: 1

p.campbell
p.campbell

Reputation: 100577

Try this to get all the products and the number of reviews on each:

SELECT P.*, IFNULL(COUNT(R.product_ID),0) AS NumReviews
FROM Product AS P
LEFT JOIN Review AS R ON R.product_id = p.product_id
ORDER BY  COUNT(R.product_ID) DESC

Upvotes: 1

webbiedave
webbiedave

Reputation: 48897

Since you're presumably selecting COUNT('review_id') in your query, you can simply add ORDER BY COUNT('review_id') DESC at the end.

Upvotes: 2

Related Questions