按最高平均评分排序

时间:2015-08-18 00:04:37

标签: php mysql sql

我有一个名为ranks的表,其中存储了1-7值,并将其与itemuser ID相关联。

像这样:id | userid | value | itemid

要显示项目的评分,我计算所有值(1-7)的总和,其中itemid=?除以总行数。但是我在items表本身中没有存储任何值。

取平均评分:

    // 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;

但我不知道如何按最高评分排序,除非我将评分存储在items表格中。是否可以使用单独的ranks表?

2 个答案:

答案 0 :(得分:2)

您可以使用avg()按其最高评分检索itemid。这与获得总和并除以计数相同:

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

答案 1 :(得分:1)

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;

您可以获得平均评分并使用子查询对其进行排序。