0

For a table like this:

username        | time
---------------------------------------
animuson        | 0.678
aP*animuson     | 0.967
animuson        | 0.567
qykumsoy        | 0.876

I'm trying to find a way in MySQL to order these by times and then find the position where username occurs and username is only counted once. So, if I'm searching for username 'qykumsoy', it should return 2, because both 'animuson' times are faster, but only the fastest one counts, then 'qykumsoy' is the next fastest after that. I can get them grouped and ordered, but how do I find what position that username is at? I figured just doing this in MySQL might be faster than looping through all the results in PHP, correct me if I'm wrong.

What I've thought of so far:

SELECT * FROM `times` ORDER BY MIN(`time`) GROUP BY `username`

I'm not very well experienced with MySQL, only the basic stuff. Any ideas?

4

1 回答 1

0

您所追求的是与表中数据相关的排名 - MySQL 没有任何排名/分析/窗口功能,但您有两个选择 - 这个:

SELECT x.rank
   FROM (SELECT t.username, 
                         t.time,
                         (SELECT COUNT(*)
                              FROM TABLE y
                             WHERE y.time <= t.time) AS rank
                 FROM TABLE t) x
 WHERE x.username = 'qykumsoy'

...或使用变量:

SELECT x.rank
   FROM (SELECT t.username, 
                         t.time,
                         @rownum := @rownum + 1 AS rank
               FROM TABLE t
                  JOIN (SELECT @rownum := 0) r
         ORDER BY t.time DESC) x
 WHERE x.username = 'qykumsoy'
于 2010-07-27T02:51:04.470 回答