0

我有一张照片排名表。我想根据 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);
4

4 回答 4

0
SELECT rating1+rating2+rating3 AS total FROM `test` ORDER BY total  DESC

这个?

于 2012-04-18T19:24:43.120 回答
0

默认情况下,MySql 中的记录已按升序返回,但您可能希望使用DESC关键字,而不是ASC. ratings1如果您要选择前 5 个,为什么要对列进行平均?

重新阅读问题,重新提交新答案。

$sth = "SELECT * FROM pics ORDER BY (rating1 + rating2 + rating3) desc LIMIT 5";
于 2012-04-18T19:25:28.590 回答
0

您解释问题的方式不清楚,这可能是您想要的:

SELECT photoID, AVG((rating1+rating2+rating3)/3) as rating
FROM votes GROUP BY photoID ORDER BY rating DESC LIMIT 5
于 2012-04-18T19:30:59.740 回答
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
于 2012-04-18T20:39:33.317 回答