如何循环表中的每个值并找到平均值

时间:2017-01-21 20:34:46

标签: php mysql sql mysqli

我是初学程序员,我正在尝试查找供应商2的平均用户评级 我的步骤如下:
1.用户'Jimmy'给供应商2 评分3 (评分超过5)
2.TABLE vendoratings 已更新 enter image description here
3. ratingstot.php 然后在<所有供应商之前计算评级响应数量的总和< strong>更新下面显示的表 vendortotalratings
enter image description here
4.User'Jimmy'点击'查看平均用户评分'
5.检索 totalratings totalno 的值并将其划分为Javascript

var average= totalratings/totalno

6。 totalno将显示给用户Jimmy。结束

问题
 1.我需要帮助在ratingstot.php中形成for或while循环来计算评级和否。属于供应商X的响应,然后在每个供应商的 vendortotalratings 表中插入它们 ratingstot.php

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
error_reporting(E_ERROR);
try{
    //Database connection
    $conn = new mysqli("localhost", "XXXXXXXX_XXX", "XXXXXXXX", "XXXXXXXX");

    //Unsure how to loop this to make vendor new value every loop
    for($i=0; $i<=6; $i++){
    $vendor = ??

        //Calculate sum of ratings from table ratings
        $result = $conn->query("SELECT SUM(ratings) FROM ratings WHERE vendorid = '".$vendorid."' ");
        $row = mysqli_fetch_array($result);
        $totalratings = $row[0];

        //Calculate no. of responses (by counting no. of rows)
        $result1 = $conn->query("SELECT * FROM ratings WHERE vendorid = '" . $vendorid."' ");
        $totalno = mysqli_num_rows($result);

        //inserting the results into the table
        $query  = " UPDATE vendortotalratings SET ";
        $query .= " totalratings = '". $totalratings ."', totalno='".$totalno."' ";
        $query .= " WHERE vendorid = '". $vendorid ."'";
        $result2 = $conn->query($query);

    }
    echo($outp);
}

catch(Exception $e) {
    $json_out =  "[".json_encode(array("result"=>0))."]";
    echo $json_out; 
}
?>
  1. 我不知道如何循环这个,是否有更简单的步骤来计算每个供应商的平均评级?

2 个答案:

答案 0 :(得分:1)

该问题并未阐明如何首先在vendortotalratings表中插入记录。因此,假设此表中已存在每个供应商的记录,则不必编写全新的循环。

更新vendortotalratings
SQL可以在单个查询中计算总评级及其计数,然后可以替换您拥有的循环。

UPDATE vendortotalratings vtr
       INNER JOIN 
       (    
         SELECT vendorid, SUM(ratings) AS sumratings, COUNT(ratings) AS countratings 
                FROM vendoratings 
         GROUP BY vendorid
       ) vr
    ON  vtr.vendorid    =   vr.vendorid
    SET 
       vtr.totalratings =   vtr.totalratings + vr.sumratings
      ,vtr.totalno      =   vtr.totalno      + vr.countratings 


计算平均值:
至于你的第二个问题,要计算平均值,你可以运行以下查询,它将为你提供运行时结果:

SELECT vendorid, totalratings, totalno, 
       CAST((totalratings/totalno) AS DECIMAL(10, 2)) AS avgrating 
FROM vendortotalratings;

如果您从结果中获取关联数组,或者使用适当的索引号(在本例中应为{),则可以使用avgrating直接在PHP中访问变量$row['avgrating'] {1}}

答案 1 :(得分:1)

您可以像这样简化所需的解决方案,而不是所有这些复杂的事情: (假设:我假设 vendorid 评级 totalratings totalno 列的类型为{{1 }})

  • 使用以下声明/查询获取与每个 vendorid 对应的总计 totalno

    INT
  • 现在使用$result = $conn->query("SELECT vendorid, SUM(ratings) as totalratings, COUNT(userid) as totalno FROM vendorratings GROUP BY vendorid"); 循环遍历$result结果集。

    while()
  • 在上述while($row = $result->fetch_array()){ ... } 循环的每次迭代中,检查 vendorid 值是否已存在。如果存在,则while()行包含总计 totalno ,否则UPDATE新行包含 vendorid 总计 totalno

    INSERT

{strong} while($row = $result->fetch_array()){ $res = $conn->query("SELECT vendorid FROM vendortotalratings WHERE vendorid = " . $row['vendorid']); if($res->num_rows){ // Update the existing row $conn->query("UPDATE vendortotalratings SET totalratings = ".$row['totalratings'].", totalno = ".$row['totalno']." WHERE vendorid = ".$row['vendorid']); echo "Affected rows: " . $conn->affected_rows . '<br />'; }else{ // Insert a new row $res = $conn->query("INSERT INTO vendortotalratings VALUES(".$row['vendorid'].", ".$row['totalratings'].",".$row['totalno'].")"); if($res) echo "New row inserted <br />"; } } 块的完整代码就像这样:

try-catch