按平均值优化sql结果集

时间:2011-07-22 19:42:37

标签: mysql sql database

我有以下SQL行返回db中评分为10的所有fanart ...当前它可以工作,但不是最初的预期...

我想要的是返回结果,其中fanart的平均评分是10 ...评级表中的每个fanart行可以引用相同的itemid,允许我们每个peice有多个用户评级艺术品...我想它只返回不同的itemid所有评级的平均值是10。

SELECT DISTINCT g.gametitle, 
                p.name, 
                g.id, 
                b.filename 
FROM   games AS g, 
       banners AS b, 
       platforms AS p, 
       ratings AS r 
WHERE  r.itemid = b.id 
       AND r.rating = '10' 
       AND g.id = b.keyvalue 
       AND r.itemtype = 'banner' 
       AND b.keytype = 'fanart' 
       AND g.platform = p.id 
ORDER  BY Rand() 
LIMIT  6; 

希望能比我更聪明的人能够解决这个问题!

我尝试创建一个使用AVG()函数但不起作用的子查询。

期待一些发人深省的回复!

1 个答案:

答案 0 :(得分:2)

这需要 AGGREGATION

   SELECT g.gametitle, 
          p.name, 
          g.id, 
          b.filename 
   FROM   games AS g, 
          banners AS b, 
          platforms AS p, 
          ratings AS r 
   WHERE  r.itemid = b.id 
          AND g.id = b.keyvalue 
          AND r.itemtype = 'banner' 
          AND b.keytype = 'fanart' 
          AND g.platform = p.id 
   GROUP BY g.gametitle, 
            p.name, 
            g.id, 
            b.filename 
   HAVING AVG(r.rating) = 10