[英]MySQL Group returns multiple results when aggregate function is equal
我正在嘗試從數據庫表中獲取結果列表(“結果”),但是,每個成員可能都提交了多個結果,因此我希望獲得他們的最佳時間。
下面的查詢有效(盡管我不確定它是否有效),除非同一競爭對手在同一時間獲得了多個結果。 (例如,競爭對手2得分兩次32.15秒)。 在這種情況下,我為此競爭對手得到兩行,而不是我想要的那一行。
SELECT result_id FROM (
SELECT member_id,MIN(time) AS mintime FROM result
JOIN member_result ON result.id = member_result.result_id
WHERE event_id = ?
GROUP BY member_id ORDER BY mintime ) AS x
JOIN result ON result.time = x.mintime
JOIN member_result ON member_result.result_id = result.id
AND member_result.member_id = x.member_id
任何解決該問題的建議都會收到。
編輯:表結構按要求;
member_result (TABLE)
id int unsigned (10)
result_id int unsigned (10)
member_id int unsigned (10)
club_id int unsigned (10)
result (TABLE)
id int unsigned (10)
time decimal (6)
is50mPool BIT ()
date date ()
verified BIT ()
verified_date timestamp ()
verified_comment varchar (255)
hasEmailed BIT ()
enabled BIT ()
event_id int unsigned (10
樣本問題:結果:事件#2的ID#1,時間60成員_結果:ID#1,result_id 1,成員ID 3,結果:事件#2的ID#2,時間60成員_結果:ID#2,結果ID,2,成員ID 3
我只想返回一行,其中任何一個result_id-當前的兩行都是在最小時間相等的情況下返回的。
編輯:
您可以嘗試使用MIN或MAX,具體取決於哪一個更吸引您使用ID,然后只有一行:
喜歡:
SELECT result_id FROM (
SELECT member_id, MIN(member_result.id) as member_resultID ,MIN(time) AS mintime FROM result
JOIN member_result ON result.id = member_result.result_id
WHERE event_id = 2
GROUP BY member_id ORDER BY mintime )
AS x
JOIN result ON result.time = x.mintime
JOIN member_result ON member_result.result_id = result.id
AND member_result.id = x.member_resultID
對於第一個用戶,這僅返回給定事件的MIN時間。 (因此只有一行而不是兩行)
這是一個SqlFiddle 。
SELECT Distinct result_id FROM (
SELECT member_id,MIN(time) AS mintime FROM result
JOIN member_result ON result.id = member_result.result_id
WHERE event_id = ?
GROUP BY member_id ) AS x
JOIN result ON result.time = x.mintime
JOIN member_result ON member_result.result_id = result.id
AND member_result.member_id = x.member_id
你嘗試過這個嗎?
實際上,這就像在外部查詢上再次進行分組一樣簡單-最初由於在沒有ORDER BY的情況下我就已經有了LIMIT語句,而由於基於GROUP BY的查詢,在沒有限制的情況下,最初似乎沒有任何作用壞了。
SELECT result_id FROM (
SELECT member_id,MIN(time) AS mintime FROM result
JOIN member_result ON result.id = member_result.result_id
WHERE event_id = ?
GROUP BY member_id ORDER BY mintime ) AS x
JOIN result ON result.time = x.mintime
JOIN member_result ON member_result.result_id = result.id
AND member_result.member_id = x.member_id
GROUP BY member_result.member_id
感謝所有貢獻者!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.