2013-06-13 63 views
1

我試圖從一個由spot_id和vote_type分組的表中得到最大的行總數,但我需要的其他字段(video_id)不在組中,所以我這就是爲什麼它會在結果集中給出錯誤的video_id。我的查詢出了什麼問題?SQL MAX與GROUP BY得到錯誤的非分組字段

查詢:

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' 
+0

您已經選擇其中沒有添加VIDEO_ID部分分組,所以服務器可以自由選擇任何列..參考http://dev.mysql.com/doc/refman/5.0/en/group-by-extensions.html – Meherzad

+0

我看到...我知道一些隨機選擇正在進行,但不知道如何構建查詢。謝謝! –

回答

1

如果沒有按video_id字段進行分組,您將收到來自相應分組字段的仲裁值。

一種選擇是加入到了極致查詢本身的結果 - 是這樣的:

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 
+0

非常感謝你! –

+0

+ +1爲更好的MYSQL技能比我 –

+0

@GustavoMatias - np,很高興我可以幫助! – sgeddes

0

嘗試增加VIDEO_ID到最後一組由