1

我有用户可以评价的体育赛事。所有数据都存储在 Mysql 数据库中。

评分表:

rating_id PK 
organization float //subrating
value_for_money float //subrating
fun_factor float //subrating
facilities float //subrating
event_id int
user_id int

事件表:

event_id PK
event_name varchar

有没有办法可以使用 Mysql 查询来加入表并对它们进行排序,以便我可以检索子评分中平均评分最高的 3 个事件?

4

3 回答 3

3

我想可能是这样的:

SELECT e.event_id, event_name, avg_rating
FROM Event_table e
JOIN (
    SELECT event_id, MAX((organization+value_for_money+fun_factor+facilities)/4) avg_rating
    FROM Ratings_table
    GROUP BY event_id
    ORDER by avg_rating DESC
    LIMIT 3) r
ON e.event_id = r.event_id
于 2013-10-03T10:39:23.397 回答
1

这将是一个非常复杂的查询,要在一个 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 中对多维数组进行排序

于 2013-10-03T10:43:16.740 回答
0

尝试这个::

Select 
distinct r.eventId
from 
ratingTable r
inner join eventTable  e on (r.eventId=e.eventId)
order by rating_id limit 3

但它也可以通过

Select 
    distinct r.eventId
    from 
    ratingTable r
    inner join eventTable 
order by rating_id limit 3
于 2013-10-03T10:26:44.150 回答