2

我有一个用于照片评分的数据库表,并且想要检索评分最高的照片。我知道我需要根据从最高到最低排序的平均评分来执行此操作。DB 表如下所示:

id  rating  rated_photo_id 
--  ------  ------------- 
1   5       1       
2   6       1
3   3       2
4   4       1
5   7       2

在 SQL 查询中执行此计算是否有效甚至可能?如果没有,维护第二个表来存储每个 photo_id 的平均值是否有意义?

4

4 回答 4

3

几乎所有数据库都可以做到这一点。查看 MySQL 的聚合函数。

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html

具体http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_avg为您的问题。

于 2013-01-07T21:21:47.157 回答
2

是的,假设您在rated_photo_id 列上有一个索引,那么计算平均值既简单又高效

 select rated_photo_id, AVG(rating) as average_rating 
       from photos group by rated_photo_id order by average_rating desc

对于特定的照片可以指定一个 id:

 select rated_photo_id, AVG(rating) 
     from photos where rated_photo_id = 2 group by rated_photo_id 

理想情况下,您的索引将是 (rated_photo_id, rating) 以覆盖这些查询——从而实现最快的执行。

于 2013-01-07T21:22:36.333 回答
2

您不需要第二张桌子。评级表包含您需要的信息。使用MySQL 聚合函数GROUP BY

SELECT rated_photo_id, AVG(rating) AS AverageRating, COUNT(*) AS NumberOfRatings
FROM rating_table
GROUP BY rated_photo_id
ORDER BY AverageRating DESC

输出:

+----------------+---------------+-----------------+
| rated_photo_id | AverageRating | NumberOfRatings |
+----------------+---------------+-----------------+
|              1 |        5.0000 |               3 |
|              2 |        5.0000 |               2 |
+----------------+---------------+-----------------+
于 2013-01-07T21:23:17.250 回答
1

您应该能够按照片 ID 进行分组,并在创建组时获得平均值。

SELECT rated_photo_id , AVG(rating) as rating
FROM photos 
GROUP BY rated_photo_id
ORDER BY rating DESC
于 2013-01-07T21:23:10.277 回答