简体   繁体   English

按最高平均评分排序

[英]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. 我有一个名为ranks的表,该表存储1-7值,并将其与itemuser ID连接。

Like this: id | userid | value | itemid 像这样: id | userid | value | itemid id | userid | value | itemid id | userid | value | itemid . id | userid | value | itemid

To display an item's rating, I calculate the sum of all the values (1-7) where itemid=? 为了显示项目的等级,我计算了所有值的总和(1-7),其中itemid=? and divide it by the total number of rows. 并将其除以总行数。 But I have no value stored in the items table itself. 但是我没有任何价值存储在items表本身。

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. 但是我不知道如何按最高评分排序,除非我将评分存储在items表本身中。 Is it possible with the separate ranks table? 单独的ranks表可以吗?

You can use avg() to retrieve itemid's by their highest rating. 您可以使用avg()按其最高评分检索itemid。 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
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. 您可以获取平均评分并使用子查询对其进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM