是否可以使用mysql执行计算?

时间:2013-01-07 21:19:26

标签: mysql sql

我有一个用于照片评级的数据库表,想要检索评分最高的照片。我知道我需要根据从最高到最低排序的评级的平均值来做到这一点。 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 个答案:

答案 0 :(得分: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

答案 1 :(得分: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)覆盖这些查询 - 从而最快地执行。

答案 2 :(得分:2)

你不需要第二张桌子。评级表包含您需要的信息。使用MySQL aggregate functions with 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 |
+----------------+---------------+-----------------+

答案 3 :(得分:1)

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

SELECT rated_photo_id , AVG(rating) as rating
FROM photos 
GROUP BY rated_photo_id
ORDER BY rating DESC