首页 > 解决方案 > 部分获取有序行

问题描述

你好那里的开发人员,

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

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

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

标签: phpmysqlsqlsql-order-by

解决方案


一种方法使用子查询和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
) ;

这将返回 21 行,包括指定的用户。


推荐阅读