【问题标题】:Get the rank of a user between 6 others with 2 higher and 2 lower scores in a score table [duplicate]在分数表中获取用户在其他 6 人之间的排名,其中 2 分较高和 2 分较低 [重复]
【发布时间】:2018-01-09 23:11:19
【问题描述】:

我有一个非常简单的 MySQL 表,用于保存高分。看起来是这样的:

Id     Name     Score

到目前为止一切顺利。问题是:我如何获得用户排名?当我有用户 id 时,我如何获得一些(例如 2 个)得分较高的用户和 2 个得分较低的用户之间的用户排名。

一个例子

Id  Name    Score
1   Ida     100
2   Boo     58
3   Lala    88
4   Bash    102
5   Assem   99
6   cha     105
7   phib    30

在这种情况下,结果会是这样的:

Id  Name    Score
4   Bash    102
1   Ida     100
5   Assem   99
3   Lala    88
2   Boo     58

【问题讨论】:

  • 你试过什么?你知道ORDER BY吗?
  • 他人之间的关系;不完全是另外 6 个 :)
  • 我知道order by,但这种情况无法解决
  • 使用联合解决了问题的一方面。另一方面是我没有分数。我只有 id

标签: mysql sql rank


【解决方案1】:

ORDER BY 按您选择的列对查询结果进行排序,默认为升序。正确的查询是:

SELECT * FROM [Table] ORDER BY Score DESC

更多信息可以在here找到。

【讨论】:

  • 我只有 id 没有得分
  • @user3084088 不确定这是否相关,但在 SQL 中,从 idScore 很容易...
【解决方案2】:

这是一种方法:

(select t.*
 from t
 where t.score >= (select t2.score from t t2 where t2.id = 5)
 order by score asc
 limit 3
) union all
(select t.*
 from t
 where t.score < (select t2.score from t t2 where t2.id = 5)
 order by score asc
 limit 2
)
order by score desc;

【讨论】:

    猜你喜欢
    • 2018-03-31
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    • 2019-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多