我有一个MySQL声明可以从用户表中取回前15个分数。
select @rownum:=@rownum+1 'rank', driverName, teamColour, totalScore, totalTime, didTyreChange from entries p, (SELECT @rownum:=0) r WHERE totalTime > 1000 and progress = 19 order by totalScore desc, totalTime asc limit 15
条件是,玩家必须完成所有问题(其中进度= 19)并且最终时间必须超过1秒(总时间> 1000)。该陈述还将其等级作为变量返回(@rownum:= @ rownum + 1' rank')。
此查询的结果如下
我现在想做的是,将结果扩展到仅显示玩家的最高分。我查看了DISTINCT
和GROUP BY
但是使用以下GROUP BY
语句获得了这些结果
select @rownum:=@rownum+1 'rank', driverName, teamColour, totalScore, totalTime, didTyreChange from entries p, (SELECT @rownum:=0) r WHERE totalTime > 1000 and progress = 19 group by driverName order by totalScore desc, totalTime asc limit 15
并且DISTINCT
没有,因为我收到错误代码1064.我已经尝试了两个
select @rownum:=@rownum+1 'rank', DISTINCT(driverName), teamColour, totalScore, totalTime, didTyreChange from entries p, (SELECT @rownum:=0) r WHERE totalTime > 1000 and progress = 19 order by totalScore desc, totalTime asc limit 15
和
select DISTINCT driverName, @rownum:=@rownum+1 'rank', teamColour, totalScore, totalTime, didTyreChange from entries p, (SELECT @rownum:=0) r WHERE totalTime > 1000 and progress = 19 order by totalScore desc, totalTime asc limit 15
两者均未提供所需结果。我想知道是否有一种简单的方法可以在语句中实现这一点,或者在PHP方面做到这一点。
期望的结果L
viper 1 9810
Maverick 2 25420
Racer roasty 3 28850
.. .
... 15
换句话说,没有用户应该在结果中出现两次,只为每个用户显示最快的totalTime。
在这里修剪SQLFiddle http://sqlfiddle.com/#!2/36d3dc/7(达到8000个字符限制)。
答案 0 :(得分:2)
SELECT @i:=@i+1 rank, a.*
FROM
( SELECT x.*
FROM entries x
JOIN (SELECT drivername, MIN(totaltime) min_totaltime FROM entries WHERE progress = 19 AND totaltime > 1000 GROUP BY drivername) y
ON y.drivername = x.drivername
AND y.min_totaltime = x.totaltime
) a
, (SELECT @i:=0) i
ORDER
BY totalScore desc, totalTime asc;
答案 1 :(得分:0)
如果我理解您的问题,那么以下查询将对您有所帮助:
select *,@rownum:=@rownum+1 as 'rank' from (select * from (select driverName, teamColour, totalScore, totalTime, didTyreChange from entries p WHERE totalTime > 1000 and progress = 19 order by totalScore desc, totalTime asc )a group by driverName)c , (select @rownum:=0)f
答案 2 :(得分:0)
这应该做:
select @rownum:=@rownum+1 'rank', driverName, totalScore, MIN(totalTime)
from entries p, (SELECT @rownum:=0) r
WHERE totalTime > 1000 and progress = 19
group by driverName
order by totalScore desc, totalTime asc