0

我正在尝试从数据库表(“结果”)中获取结果列表,但是,每个成员可能已经提交了多个结果,我希望检索他们的最佳时间。

下面的查询有效(尽管我不确定它是否有效),除非有来自同一个竞争对手的多个结果且得分相同的情况。(例如,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

示例问题:结果:id#1 for event#2,time 60 member_result:id#1,result_id 1,member_id 3 结果:id#2 for event#2,time 60 member_result:id#2,result_id 2,member_id 3

我只想返回一行,其中一个是 result_id - 目前两行都返回,因为最短时间相等。

4

3 回答 3

1

编辑:

您可以尝试使用 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

于 2012-08-27T14:55:59.977 回答
0
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 

你试过这个吗?

于 2012-08-27T14:40:05.353 回答
0

实际上,事实证明这就像在外部查询上再次分组一样简单 - 由于 GROUP BY 查询的限制,我在没有 ORDER BY 的限制之前有一个 LIMIT 语句,最初似乎不起作用的东西坏了。

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

感谢所有做出贡献的人!

于 2012-08-29T18:32:06.937 回答