这将是一个非常复杂的查询,要在一个 mysql 查询中完成所有操作。我个人会在 PHP 中执行此操作。这是如何在 PHP 和 MySQLi 中执行此操作的示例
$ratings = array();
$query = "SELECT * FROM ratings";
$results = $dbConn->query($query);
//First we load all results into a big array.
while($row = $results->fetch_assoc($results) {
if(!isset($ratings[$row['rating_id']]) {
$ratings[$row['event_id']]['count'] = 0;
}
$ratings[$row['event_id']]['count']++;
$ratings[$row['event_id']]['organisation'] += $row['organisation'];
$ratings[$row['event_id']]['value_for_money'] += $row['value_for_money'];
$ratings[$row['event_id']]['fun_factor'] += $row['fun_factor'];
$ratings[$row['event_id']]['facilities'] += $row['facilities'];
}
//Now we go through each event and average out the results.
$averages = array();
foreach($ratings as $event_id => $data) {
$averages[$event_id]['organisation'] = $data['organisation'] / $data['count'];
$averages[$event_id]['value_for_money'] = $data['value_for_money'] / $data['count'];
$averages[$event_id]['fun_factor'] = $data['fun_factor'] / $data['count'];
$averages[$event_id]['facilities'] = $data['facilities'] / $data['count'];
}
//Now we can sort by whatever we want to:
或者,如果您想要所有 4 个评级的平均值,您可以在最后使用此位来代替平均值:
$averages = array();
foreach($ratings as $event_id => $data) {
$averages[$event_id] = (($data['organisation'] + $data['value_for_money'] + $data['fun_factor'] + $data['facilities']) / 4) / $data['count'];
}
请注意:我没有测试过这段代码......你应该自己检查它的错误。
对于排序,请检查排序多维数组的各种堆栈溢出答案。按值对多维数组进行排序
或如何在 PHP 中对多维数组进行排序