【发布时间】:2020-02-05 06:36:40
【问题描述】:
我为新闻文章创建了一个简单的评级系统。新闻文章存储在称为“文章”的数据库表中。每篇文章都有一个唯一的 id,从 1 开始。
所以我有 2 篇文章,ID 1 和 ID 2。
我还有一个名为“ratings”的表,其中包含用户唯一 ID、文章 ID 和用户给出的评分。
如果我给 ID 2 的文章 5/5 星评级,它将进入“评级”表,文章 ID 为 2,我的用户 ID 和评级为 5。
我已经弄清楚如何显示每篇文章的平均评分,但我想了解如何按降序显示文章的最佳平均评分。这有可能吗?这怎么可能?
这是我找到平均值的方法:
<?
$votesForThis = 0;
$sql = "SELECT * FROM ratings WHERE articleID = ".$articleID." ORDER BY id ASC";
// Check if there are results
if ($result = mysqli_query($con, $sql)) {
// Loop through each row in the result set
while($row = mysqli_fetch_assoc($result)) {
$votesForThis++;
}
}
$result = mysqli_query($con, 'SELECT SUM(vote) AS vote_sum FROM ratings WHERE articleID=' . $articleID);
$row = mysqli_fetch_assoc($result);
$voteSum = $row['vote_sum'];
$averageVotes = $voteSum / $votesForThis;
?>
【问题讨论】: