不能做SUM的SUM?

时间:2012-08-01 01:52:27

标签: mysql sql

以下查询似乎有一个问题来计算“ratingValue”,因为SUM中有SUM(h.liked)。

SELECT d.itemID1 as item, 
    sum(d.sum + d.count*SUM(h.liked))/sum(d.count) as ratingValue
FROM history h, dev d 
WHERE h.userID=:id_user
    AND d.itemID1<>h.itemID 
    AND d.itemID2=h.itemID 
GROUP BY d.itemID1,h.itemID 

为了更好地理解,这是原始的和有效的查询(来自Slop One算法):

我只是将“rating”表替换为“history”,因为在我的情况下,r.ratingValue是用户给itemID的所有“like”的总和(=&gt; r.ratingValue = SELECT SUM(like) )FROM FROM GROUP BY h.itemID):

SELECT d.itemID1 as item, 
    sum(d.sum + d.count*r.ratingValue)/sum(d.count) as ratingValue 
FROM rating r, dev d 
WHERE r.userID=$userID 
    AND d.itemID1<>r.itemID 
    AND d.itemID2=r.itemID 
GROUP BY d.itemID1

1 个答案:

答案 0 :(得分:2)

正如错误消息所示,您不能使用下一个聚合函数。我想你的意思是:

SELECT d.itemID1 as item, 
       sum(d.sum + d.count*h.sumliked)/sum(d.count) as ratingValue
FROM (select h.userId, h.itemId, sum(h.liked) as sumliked
      from history h
      group by h.userId, h.itemId
     ) h join
     dev d 
     on h.userID=:id_user AND
        d.itemID1<>h.itemID AND
       d.itemID2=h.itemID 
GROUP BY d.itemID1

也就是说,您需要单独进行聚合,在这种情况下使用子查询。我还修复了查询中的连接语法。