计算mysql中的所有原始值

时间:2015-01-12 11:36:54

标签: php mysql mysqli

我正在做的是将用户评级和评论保存到表中,然后从数据库中调用它。现在我要做的是添加所有评级(例如:5 + 4 + 3 = 12),然后将其除以评级计数(12/3 = 4)并获得平均评级或总评分。

我可以显示评论,但如何添加评级列中的所有值并获得平均值。

if (mysqli_num_rows($mesult) > 0) {
  $count = mysqli_num_rows($mesult);
  echo '<p class="">'.$count.' Reviews</p>';
  while($row = mysqli_fetch_assoc($mesult)) {
    $name =$row["name"];
    $text =$row["text"];
    $heading =$row["heading"];
    $rating =$row["rating"];
    echo '<div class="review"  itemscope itemtype="http://schema.org/Review">  <meta itemprop="itemReviewed" content ="'.$title.'"/> <p class="heading"><strong>'.$heading.'</strong></p><div class="ratings" itemprop="reviewRating" itemscope itemtype="http://schema.org/Rating"> <meta itemprop="worstRating" content = "1"/><span itemprop="ratingValue">'.$rating.'</span>/<span itemprop="bestRating">5</span></div><p class="reviewtext" itemprop="description">'.$text.'</p><div class="reviewby"  itemprop="author" itemscope itemtype="http://schema.org/Person"><span itemprop="name">'.$name.'</span></div></div>';
}

我正在查询的是

$loutput ="SELECT * FROM rating
WHERE product=$ID";
$mesult = mysqli_query($conns,$loutput);

3 个答案:

答案 0 :(得分:5)

您还可以使用MySQL的AVG()来计算平均评分:

SELECT AVG(rating) AS avgRating FROM myTable;

这是将结果舍入为X小数的方法:

 SELECT ROUND(AVG(rating), X) AS avgRating FROM myTable;

答案 1 :(得分:2)

$loutput ="SELECT AVG(Column_name) as avg FROM rating WHERE product='".$ID."'";

$mresult=mysqli_fetch_assoc(mysqli_query($loutput));

echo $mresult['avg'];

答案 2 :(得分:0)

使用聚合函数 得到average使用avg()

从评级中选择平均值(评级);

相关问题