带有GROUP BY的SQL MAX获取错误的非分组字段

时间:2013-06-13 04:07:29

标签: mysql group-by max field

我正在尝试从spot_id和vote_type分组的表中获取最大总行数,但我需要的另一个字段(video_id)不在组中,所以我猜这就是为什么它在结果中给出了错误的video_id组。我的查询有什么问题?

查询:

SELECT 
    max(total_votes) as total, spot_id, vote_type, video_id 
FROM 
    (
    SELECT 
        count(*) as total_votes, spot_id, video_id, vote_type 
    FROM 
        spot_video_votes 
    GROUP BY 
        spot_id, video_id, vote_type
    ) AS t
GROUP BY 
    spot_id, vote_type

子查询结果:

total_votes, spot_id, video_id, vote_type
'1','1','2','OWN'
'1','1','3','OWN'
'4','1','4','OWN' -- should pick this
'1','2','3','FAIL'
'2','2','3','OWN' -- this
'2','2','4','FAIL' -- and this
'1','2','4','OWN'

实际结果:

total, spot_id, video_id, vote_type
'4','1','2','OWN'
'2','2','3','FAIL'
'2','2','3','OWN'

预期结果:

total, spot_id, video_id, vote_type
'4','1','4','OWN'
'2','2','4','FAIL'
'2','2','3','OWN'

2 个答案:

答案 0 :(得分:1)

如果没有按video_id字段进行分组,您将从相应的分组字段中接收任意值。

一种选择是将max查询的结果连接到自身 - 如下所示:

SELECT t1.total_votes as total, t1.spot_id, t1.vote_type, t1.video_id 
FROM 
    (
    SELECT count(*) as total_votes, spot_id, video_id, vote_type 
    FROM spot_video_votes 
    GROUP BY spot_id, video_id, vote_type
    ) AS t1 JOIN 
    (
    SELECT max(total_votes) as max_total_votes, spot_id, vote_type, video_id 
    FROM 
        (
        SELECT count(*) as total_votes, spot_id, video_id, vote_type 
        FROM spot_video_votes 
        GROUP BY spot_id, video_id, vote_type
        ) AS t
    GROUP BY spot_id, vote_type
    ) t2 ON t1.total_votes = t2.max_total_votes 
           AND t1.spot_id = t2.spot_id 
           AND t1.vote_type = t2.vote_type

答案 1 :(得分:0)

尝试通过

将video_id添加到最后一组