【发布时间】:2020-06-07 13:45:59
【问题描述】:
我有一个名为feedbacks 的表,如下所示:
id user type
1 JOhnT Positive
2 JOhnT Negative
3 Sarah Positive
4 JOhnT Positive
5 JOhnT Neutral
....................
我需要为每个使用 PHP 的用户获取 percentage 的 POSITIVE 反馈。
我尝试过这样的事情,但我知道这是错误的:
$sql = "SELECT type, count(*),
concat(round(( count(*)/(SELECT count(*) FROM feedbacks WHERE user='JOhnT' AND type='POSITIVE') * 100 ),2),'%') AS percentage
FROM feedback
WHERE user='$email' AND type='positive' GROUP BY type";
$query = mysqli_query($db_conx, $sqlJ);
echo $sql;
有人可以就如何实现这一点提出建议吗?
编辑:
基于 cmets,这是我目前所拥有的:
$sql = "SELECT * FROM feedbacks WHERE user='JOhnT' AND type='POSITIVE'";
$query = mysqli_query($db_conx, $sql) or die(mysqli_error($db_conx));
$productCount = mysqli_num_rows($query);
if ($productCount > 0) {
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
///do I need to calculate the percentage here?//
//if so, how?////
}
}
我最终创建了一个数组,并将整个循环中的每个 $row 推入数组,然后计算如下百分比:
$c = count($values);
$array = $values;
function array_avg($array, $round=1){
$num = count($array);
return array_map(
function($val) use ($num,$round){
return array('count'=>$val,'avg'=>round($val/$num*100, $round));
},
array_count_values($array));
}
$rating = 0;
if($c > 0){
$avgs = array_avg($array);
$rating = $avgs["positive"]["avg"];
}
现在这工作正常。
【问题讨论】:
-
mysqli_error($db_conx)透露了什么? -
@FunkFortyNiner,没有错误。
-
如果您想将这些内容呼应出来,那么您的做法不正确。您正在尝试回显结果集。您需要使用循环。
-
请解释问题所在。你没有得到结果,数据不正确? PHP也与该问题相关还是这是一个查询问题?如果你想在 PHP 中计算(我不会)不要使用聚合函数,返回所有数据然后在 PHP 中聚合和计算。
-
不,你误解了他们。他们说不要在 PHP 中这样做。在 MySQL 中进行。
标签: php mysql sql group-by average