SQL在表中查找位置

时间:2013-01-14 00:53:52

标签: mysql sql

我在mySql中有一个表,其中包含用户ID和分数。

我想要做的是按分数(简单)组织表格,然后查找某个用户ID在表格中的位置。

到目前为止,我会:

SELECT * FROM table_score
ORDER BY Score DESC

我如何找到userID = '1234'的位置(即12条第10条)

2 个答案:

答案 0 :(得分:10)

以下查询将为您提供一个新列UserRank,用于指定用户排名:

SELECT 
  UserID, 
  Score, 
  (@rownum := @rownum + 1) UserRank 
FROM table_score, (SELECT @rownum := 0) t 
ORDER BY Score DESC;

SQL Fiddle Demo

这会给你类似的东西:

| USERID | SCORE | USERRANK |
-----------------------------
|      4 |   100 |        1 |
|     10 |    70 |        2 |
|      2 |    55 |        3 |
|   1234 |    50 |        4 |
|      1 |    36 |        5 |
|     20 |    33 |        6 |
|      8 |    25 |        7 |

然后,您可以将此查询放在子查询中,并使用userId进行过滤以获得该用户排名。类似的东西:

SELECT
  t.UserRank
FROM
(
   SELECT *, (@rownum := @rownum + 1) UserRank 
   FROM table_score, (SELECT @rownum := 0) t 
   ORDER BY Score DESC
) t
WHERE userID = '1234';

SQL Fiddle Demo

答案 1 :(得分:2)

对于给定的用户ID,您可以使用简单的查询执行此操作:

select sum(case when ts.score >= thescore.score then 1 else 0 end) as NumAbove,
       count(*) as Total
from table_score ts cross join
     (select ts.score from table_score ts where userId = '1234') thescore

如果您有得分和用户ID的索引,这将非常有效。

相关问题