我有一张照片排名表。我想根据3列(rating1,2,3)的平均值输出每个类别的前5张照片的ID。
说我有以下表格列(photoID,rating1,rating2,rating3)
$sth = mysql_query("SELECT * FROM votes ORDER BY AVG(rating1) ASC LIMIT 5") or die(mysql_error());
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
echo json_encode($rows);
答案 0 :(得分:0)
SELECT rating1+rating2+rating3 AS total FROM `test` ORDER BY total DESC
此?
答案 1 :(得分:0)
默认情况下,MySql中的记录已按升序返回,但您可能希望使用DESC
关键字,而不是ASC
。如果您尝试选择前5位
ratings1
列求平均值?
重新阅读问题,重新提交新答案。
$sth = "SELECT * FROM pics ORDER BY (rating1 + rating2 + rating3) desc LIMIT 5";
答案 2 :(得分:0)
您解释问题的方式尚不清楚,这可能是您想要的:
SELECT photoID, AVG((rating1+rating2+rating3)/3) as rating
FROM votes GROUP BY photoID ORDER BY rating DESC LIMIT 5
答案 3 :(得分:0)
SELECT 1 AS category
, photoID
, AVG(rating1) AS avg_rating
FROM votes
GROUP BY photoID
ORDER BY avg_rating DESC
LIMIT 5
UNION ALL
SELECT 2 AS category
, photoID
, AVG(rating2) AS avg_rating
FROM votes
GROUP BY photoID
ORDER BY avg_rating DESC
LIMIT 5
UNION ALL
SELECT 3 AS category
, photoID
, AVG(rating3) AS avg_rating
FROM votes
GROUP BY photoID
ORDER BY avg_rating DESC
LIMIT 5