frosty
frosty

Reputation: 2851

Sort by highest average rating

I have a table called ranks which stores a 1-7 value and connects it with an item and user id.

Like this: id | userid | value | itemid.

To display an item's rating, I calculate the sum of all the values (1-7) where itemid=? and divide it by the total number of rows. But I have no value stored in the items table itself.

Fetch average rating:

    // total

    $stmt = $conn->prepare("SELECT SUM(value) as total FROM ranks WHERE itemid=?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $stmt->bind_result($total);
    $stmt->fetch();
    $stmt->close();

    // num of rows

    $stmt = $conn->prepare("SELECT COUNT(value) FROM ranks WHERE itemid=?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $stmt->bind_result($count);
    $stmt->fetch();
    $stmt->close();

    $avg = $total/$count;

But I have no idea how to sort by highest rated unless I have the rating stored in the items table itself. Is it possible with the separate ranks table?

Upvotes: 1

Views: 1441

Answers (2)

Vamsi Prabhala
Vamsi Prabhala

Reputation: 49260

select itemid, total/cnt as avgrating
from
(
select itemid, sum(value) as total, count(*) as cnt
from ranks
group by itemid
) t
order by total/cnt desc;

You can get the average rating and sort it using a sub-query.

Upvotes: 1

FuzzyTree
FuzzyTree

Reputation: 32392

You can use avg() to retrieve itemid's by their highest rating. This is the same as getting the sum and dividing by the count:

select avg(value), itemid
from ranks
group by itemid
order by avg(value) desc

Upvotes: 2

Related Questions