Skip to content
Advertisement

How to sort products by average rating from another table?

I’m new to databases, so I haven’t wrapped my head around how to use joins, subqueries etc. properly. That’s why I’m very unsure how to go about sorting products by the average of another table.

Here’s my usecase:

I have a straightforward products table in this style

And in a second table, produtcs_rating, I have the five-star ratings like

Now I want to be able to sort these on the website according to the average rating (simple arithmetic mean is fine). Would something like this be working?

Or is this something where I should use a join? And if, how? Any help for a beginner would be much appreciated!

Advertisement

Answer

Join products to a query that returns the average ratings:

Or use a correlated subquery in the ORDER BY clause:

See the demo.
Results:

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement