2012-09-14 134 views
2

我有一個表叫收視率,看起來像這樣每組選擇一行?

 
Rating | Picid | User 
    8   12   6 
    7   12   6 
    9   15   7 
    5   16   7 
    9   17   8 
    10   2   8 
    7   18   3 
    10   22   12 

我想組基礎上,picid的收視率,但只能選擇每用戶評價最高的picid。我有這樣已經查詢:

SELECT *, AVG(rating) AS total FROM ratings 
    GROUP BY picid ORDER by total DESC 

眼下查詢將輸出這樣的信息:

 
Rating | Picid | User 
7.5   12   6 
    9   15   7 
    5   16   7 
    9   17   8 
    10   2   8 
    7   18   3 
    10   22   12 

所以它的基礎上的picid成功羣體的收視率,但我只需要每個用戶最高的一個。我希望它這樣的輸出信息:

 
Rating | Picid | User 
7.5   12   6 
    9   15   7 
    10   2   8 
    7   18   3 
    10   22   12 

怎麼看呢只允許每個用戶的收視率最高的picid? 如何修改我的查詢來執行此操作?

讓我知道你是否需要更多關於我所問的問題的解釋。

回答

3

你首先必須計算的平均收視爲每個(Picid,User)組合,然後找到group-wise maximum在該物化結果:

SELECT Rating, PicID, User 
FROM (
    SELECT AVG(Rating) AS Rating, Picid, User 
    FROM  ratings 
    GROUP BY Picid, User 
) t1 NATURAL JOIN (
    SELECT MAX(Rating) AS Rating, User 
    FROM  (
    SELECT AVG(Rating) AS Rating, User 
    FROM  ratings 
    GROUP BY Picid, User 
) t 
    GROUP BY User 
) t2 

看到它的sqlfiddle

+0

這看起來不錯。但我不得不承認'NATURAL'加入我的困惑:) –

+2

它不是MySQL特定的。它在SQL標準中。 –

1

我不認爲這是最好的方式,但它的工作原理:

SELECT MAX(total) as maxTotal, picid, User 
FROM 
    (SELECT *, AVG(rating) AS total 
    FROM ratings 
    GROUP BY picid 
    ORDER BY total DESC) as a 
GROUP BY User 
ORDER BY maxTotal desc; 

您可以使用此sqlfiddle嘗試其他。

+2

Yey,[It works on my machine!](http://www.ademiller.com/blogs/tech/2008/06/it-works-on-my-machine-award/) –

+0

小心爲['ONLY_FULL_GROUP_BY'](http://dev.mysql.com/doc/refman/5.1/en/server-sql-mode.html#sqlmode_only_full_group_by)設置時不提供GROUP BY中的所有非聚合列'。 –

+0

如果同一圖片已被多個用戶評分,會發生什麼情況? – eggyal