我正在尝试从数据库表('结果')获取结果列表,但是,每个成员可能已经提交了多个结果,我希望找回他们的最佳时间。
下面的查询有效(虽然我不确定它是否有效),除非同一竞争对手有多个结果且得分相同。 (例如,竞争者#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 member_result:id#1,result_id 1,member_id 3 结果:事件#2的id#2,时间60 member_result:id#2,result_id 2,member_id 3
我只想返回一行,使用result_id - 当前两行都返回,因为最小时间相等。
答案 0 :(得分: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。
答案 1 :(得分: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
你试过这个吗?
答案 2 :(得分:0)
实际上,事实证明这就像在外部查询上再次分组一样简单 - 由于我在限制之前没有ORDER BY的LIMIT语句,因为GROUP的原因通过查询打破了。
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
感谢所有贡献者!