部分获取有序行

Getting ordered rows partly

你好开发者,

我想在我的程序中创建一个排名列表,为此想要让 mysql 数据库的用户按他们的分数排序。我正在这样做:

select `name`,`points` from users order by `points` desc

为了获得更好的性能,我不希望获得所有用户,而只想获得给定用户的 10+ 和 10-,因为无论如何我都不想在程序中显示整个排名列表。有人可以帮我解决这个问题吗?

一种方法使用子查询和union all:

(select name, points
 from users
 where points <= (select u2.points from users u2 where u2.name = ?)
 order by points desc
 limit 11
) union all
(select name, points
 from users
 where points > (select u2.points from users u2 where u2.name = ?)
 order by points asc
 limit 10
) ;

这 returns 21 行,包括指定的用户。