0

我有一个users表格,我也可以在其中给这个用户打分。所以这意味着一个用户只能有一个最高分。我想要实现的是查询所有用户的前 10 个高分以及当前用户的前 5 个和下一个分数。
SQLFiddle http://sqlfiddle.com/#!2/466d0/5
目前我有一个查询,它选择所有用户,按高分降序排列,并给出每个用户的行号,所以它按分数排序。对此的工作查询如下:

SELECT u.id, u.score,
        @curRow := @curRow + 1 AS POSITION
FROM    b_users u
JOIN    (SELECT @curRow := 0) r
ORDER BY u.score DESC , u.id ASC

输出是正确的

| ID | SCORE | POSITION |
|----|-------|----------|
|  5 |   500 |        1 |
| 20 |   433 |        2 |
| 14 |   432 |        3 |
| 18 |   350 |        4 |
| 19 |   320 |        5 |
| 16 |   201 |        6 |
| 17 |   150 |        7 |
| 12 |    90 |        8 |
| 23 |    90 |        9 |
| 11 |    70 |       10 |
| 22 |    70 |       11 |
| 10 |    60 |       12 |
|  9 |    50 |       13 |
| 21 |    40 |       14 |
|  4 |    12 |       15 |
|  3 |    10 |       16 |
|  8 |    10 |       17 |
| 13 |    10 |       18 |
| 24 |    10 |       19 |
| 15 |     8 |       20 |
|  1 |     5 |       21 |
|  2 |     3 |       22 |
|  6 |     3 |       23 |
|  7 |     2 |       24 |

Once again, SQLFiddle for that is http://sqlfiddle.com/#!2/466d0/5
Now I'm stuck on how to extend this query so that it only outputs the top 10 position and for example if my ID is 8 (position 17) then it also outputs positions from 12 to 22.

4

1 回答 1

2

Try wrapping it in an outer query, like so:

SELECT * 
FROM (
  SELECT u.id, u.score,
        @curRow := @curRow + 1 AS POSITION
  FROM    b_users u
  JOIN    (SELECT @curRow := 0) r
  ORDER BY u.score DESC , u.id ASC) origQuery
WHERE origQuery.position <= 10
   OR (origQuery.position >= (17 - 5) AND origQuery.position <= (17 + 5))
于 2013-10-19T23:01:53.857 回答