【问题标题】:count all raw values in mysql计算mysql中的所有原始值
【发布时间】:2015-01-12 11:36:54
【问题描述】:

我所做的只是将用户评分和评论保存到表中,然后从数据库中调用它。现在我要做的是添加所有评分(例如: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);

【问题讨论】:

    标签: php mysql mysqli


    【解决方案1】:

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

    SELECT AVG(rating) AS avgRating FROM myTable;
    

    这是将结果四舍五入到小数点 X 的方式:

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

    【讨论】:

      【解决方案2】:
      $loutput ="SELECT AVG(Column_name) as avg FROM rating WHERE product='".$ID."'";
      
      $mresult=mysqli_fetch_assoc(mysqli_query($loutput));
      
      echo $mresult['avg'];
      

      【讨论】:

      • $loutput ="SELECT AVG(rating) FROM rating WHERE product=$ID"; $mesult = mysqli_query($conns,$loutput); echo $mesult; 不起作用
      【解决方案3】:

      使用聚合函数 要获取average,请使用 avg()

      从评分中选择平均(评分);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-06
        • 2015-10-21
        • 2011-09-02
        相关资源
        最近更新 更多