2

所以我有这个游戏数据库,我有几个用户,他们有字段,id,name,points

我需要一个特定用户的排名表,可以看到它的位置与点数的关系,表中有 8 个位置的空间,所以我正在寻找一种方法来执行以下操作:

如果我SELECT * FROM users WHERE id = {user_id} ORDER By points选择之前的 4 个结果和之后的 3 个结果。有查询吗?结果应如下所示:

---------------------
|id   |name  |points|
---------------------
| 52  |name1 | 10   |
---------------------
| 23  |name1 | 09   |
---------------------
| 93  |name1 | 08   |
---------------------
| 12  |name1 | 07   |
---------------------
| 43  |queried_name1 | 06   |
---------------------
| 67  |name1 | 05   |
---------------------
| 32  |name1 | 04   |
---------------------
| 91  |name1 | 03   |
---------------------

我试图通过软件来实现这一点,但迭代所有结果的速度非常慢。谢谢你的帮助!

4

2 回答 2

1

就像这样,我会说,对于上述结果:

SELECT * FROM users WHERE points > (SELECT points FROM users WHERE id = {user_id}) ORDER By points ASC LIMIT 3;

对于以下结果:

SELECT * FROM users WHERE points < (SELECT points FROM users WHERE id = {user_id}) ORDER By points DESC LIMIT 4;

所以,有了一个大联盟,它会给出:

SELECT * FROM (SELECT * FROM users WHERE points > (SELECT points FROM users WHERE id = {user_id}) ORDER By points ASC LIMIT 3 ) a 
UNION
SELECT * FROM users WHERE id = {user_id}
UNION
SELECT * FROM (    SELECT * FROM users WHERE points < (SELECT points FROM users WHERE id = {user_id}) ORDER By points DESC LIMIT 4 ) b
于 2012-06-12T05:54:13.407 回答
1

您可以使用此查询 -

SELECT id, name, points FROM (
  SELECT u.*, @r:=@r+1 rank, @pos:=IF(@pos = 0 AND name = 'queried_name1', @r, @pos)
    FROM users u,
    (SELECT @r:=0, @pos:=0) t
  ORDER BY points DESC
  ) t
WHERE rank BETWEEN @pos - 4 AND @pos + 3

它按点对表进行排序,找到 name = 'queried_name1' 的记录,并选择找到的记录之前和之后的一些行。

于 2012-06-12T06:06:19.043 回答