我有用户可以评分的体育赛事。所有数据都存储在Mysql数据库中。
Ratings_table:
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_table:
event_id PK
event_name varchar
有没有办法可以使用Mysql查询加入表格并对它们进行排序,以便我可以检索子评级平均评分最高的3个事件?
答案 0 :(得分: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
答案 1 :(得分: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'];
}
请注意:我还没有测试过这段代码......你应该自己查看bug。
对于排序,请检查排序多维数组的各种堆栈溢出答案。 Sort Multi-dimensional Array by Value 或How do I Sort a Multidimensional Array in PHP
答案 2 :(得分: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