Karem
Karem

Reputation: 18103

Showing most rated in PHP and MySQL

Okay, so I got 2 tables. One holds the recipes, and the second all the ratings.

recipes_ratings:
id, rating, user_id, recipe_id

recipes:
id, name

I would like to count all the rows for each recipe. Then sort and show the recipes that are most rated and descending.

What is the simplest way to do? I have thought to make a query

SELECT * FROM recipes_ratings

And then count with a loop through the ratings, and store into array, and then sort out from that.

But can it be done simpler? One query only to do it all..or?

Upvotes: 1

Views: 129

Answers (1)

Dan Soap
Dan Soap

Reputation: 10248

Depending on how you want to calculate the overall rating per recipe, you might need to adapt the calculation. But the query should be something like this:

SELECT r.id, product, avg(rating) as average_rating
FROM recipes r 
LEFT JOIN recipes_ratings rr 
    ON (r.id=rr.recipe_id)
GROUP BY id 
ORDER BY 3 desc;

Beware, that this will also output recipes without any rating. If you don't want to have them returned, change LEFT JOIN to JOIN.

Upvotes: 1

Related Questions