0

我是 MYSQL/PHP 新手,我确信这是一个简单的问题。我正在尝试从一个表中计算几个问题和受访者的平均值,并使用该值更新组表。

例如,表答案由我想要的表 B 中的 (name, group_id, TaskClarity1, TaskClarity2, TaskClarity3) 组成 (group_id, avg(TaskClarity1,TaskClarity2,TaskClarity3))。

这就是我所拥有的...

$avg_task_clarity_1 = mysql_query("SELECT AVG(TaskClarity1) WHERE gruppid = '$group_id'");
$avg_task_clarity_2 = mysql_query("SELECT AVG(TaskClarity2) WHERE gruppid = '$group_id'");
$avg_task_clarity_3 = mysql_query("SELECT AVG(TaskClarity3) WHERE gruppid = '$group_id'");
$avg_task_clarity = ($avg_task_clarity_1+$avg_task_clarity_2+$avg_task_clarity_3)/3;
$print_task_clarity_1" UPDATE results SET results.TaskClarity = '$avg_task_clarity'"; 

if (mysql_query($print_task_clarity_1)) { echo $print_task_clarity_1; } else { echo "Error TaskClarity1: " . mysql_error(); 
4

1 回答 1

0

首先,mysql_query() 返回一个资源,然后您需要从中提取信息。您的查询不包含任何表名(我将其称为 MyTable)。此外,您可以通过一次查询获得所有三个平均值。

这是我将如何开始:

$table = "MyTable";
$sql = "SELECT AVG(TaskClarity1) AS avgClarity1,
               AVG(TaskClarity2) AS avgClarity2,
               AVG(TaskClarity3) AS avgClarity1
        FROM $table WHERE gruppid = '$group_id'";

$resource = mysql_query($sql);    //execute the query

if (! $resource = mysql_query($sql) ){
    echo "Error reading from table $table";
    die;
}

if (! mysql_num_rows($resource ) ){
    echo "No records found in $table";
}
else {
    $row = mysql_fetch_assoc($resource);   // fetch the first row
    $avg_task_clarity_1 = $row['avgClarity1'];
    $avg_task_clarity_2 = $row['avgClarity2'];
    $avg_task_clarity_3 = $row['avgClarity3'];
    $avg_task_clarity =
        ($avg_task_clarity_1+$avg_task_clarity_2+$avg_task_clarity_3)/3;

    //...
    // other stuff you want to do
}

如果这还不够有用,请发表评论,我会修改我的答案。

于 2013-04-18T14:58:41.593 回答