php - 部分获取有序行

标签 php mysql sql sql-order-by

开发者们大家好,

我想在我的程序中创建一个排名列表,为此想要让 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
) ;

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

关于php - 部分获取有序行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53132295/

相关文章:

PHP header() 函数

php - 将 Rails 模型连接到非 Rails 数据库

php - Android 中录制和传输音频的设计

mysql - 优化where语句MYSQL

php - PayPal API 定期付款

网格中的 PHP 数据循环

php - 提前查询。在mysql中对最相关的字段进行排名

PHP 从命令行输出,但不从浏览器输出

iphone - iOS简单的SQL错误

mysql - 使用连接优化 SQL 选择查询