Multi Join + Group By,每张专辑获得1行最高评分

时间:2013-06-15 22:57:57

标签: mysql join max average

我正在尝试制作图表列表并使用以下查询

SELECT 
    vmm_user.username, 
    vmm_songs.*, 
    vmm_albums.desc, 
    vmm_albums.release, 
    vmm_albums.name, 
    AVG(vmm_songrating.rating) AS ratingavg,
    COUNT(vmm_songrating.id) AS ratingcount
FROM 
    vmm_songs 
LEFT JOIN 
    vmm_user 
ON 
    vmm_songs.userid=vmm_user.id 
LEFT JOIN 
    vmm_albums 
ON 
    vmm_songs.albumid=vmm_albums.id 
LEFT JOIN  
    vmm_songrating  
ON 
    vmm_songs.id=vmm_songrating.songid 
GROUP BY 
    vmm_songs.id
HAVING 
    COUNT(vmm_songrating.id) >= 2 
ORDER BY
    AVG(vmm_songrating.rating) DESC
LIMIT 
    10

正如你所看到的,我得到的每个条目至少有2个评分,但我只想显示最高平均评分和每张专辑最少2个评分的歌曲

我试图添加像

这样的东西
MAX(AVG(vmm_songrating.rating))

在having子句中,但它没有工作

我使用php和mysql

感谢您的帮助

编辑3: mysql小提琴 http://sqlfiddle.com/#!2/677cf/1/0

只想要前3行(专辑评分最高的歌曲)

1 个答案:

答案 0 :(得分:0)

尝试下面的内容..

SELECT MAX(songs.ratingavg), [Other Columns]  
FROM (  
SELECT 
        vmm_user.username, 
        vmm_songs.*, 
        vmm_albums.desc, 
        vmm_albums.release, 
        vmm_albums.name, 
        AVG(vmm_songrating.rating) AS ratingavg,
        COUNT(vmm_songrating.id) AS ratingcount
    FROM 
        vmm_songs 
    LEFT JOIN 
        vmm_user 
    ON 
        vmm_songs.userid=vmm_user.id 
    LEFT JOIN 
        vmm_albums 
    ON 
        vmm_songs.albumid=vmm_albums.id 
    LEFT JOIN  
        vmm_songrating  
    ON 
        vmm_songs.id=vmm_songrating.songid 
    GROUP BY 
        vmm_songs.id
    HAVING 
        COUNT(vmm_songrating.id) >= 2 
    ORDER BY
        AVG(vmm_songrating.rating) DESC
    LIMIT 
        10 ) AS songs