获取一个用户在其他 6 个用户中得分高 2 分和低 2 分的排名 table
Get the rank of a user between 6 others with 2 higher and 2 lower scores in a score table
我有一个非常简单的 MySQL table 用来保存高分。看起来像这样:
Id Name Score
到目前为止一切顺利。问题是:如何获得用户排名?当我有用户 id
.[=15= 时,如何让用户在一些(如 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
按您选择的列对查询结果进行排序,默认为升序。正确的查询是:
SELECT * FROM [Table] ORDER BY Score DESC
可以找到更多信息 here。
这是一种方法:
(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;
我有一个非常简单的 MySQL table 用来保存高分。看起来像这样:
Id Name Score
到目前为止一切顺利。问题是:如何获得用户排名?当我有用户 id
.[=15= 时,如何让用户在一些(如 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
按您选择的列对查询结果进行排序,默认为升序。正确的查询是:
SELECT * FROM [Table] ORDER BY Score DESC
可以找到更多信息 here。
这是一种方法:
(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;