php - 部分获取有序行
问题描述
你好那里的开发人员,
我想在我的程序中创建一个排名列表,并为此想要让 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 行,包括指定的用户。
推荐阅读
- imagemagick - Imagemagick 没有在修剪上定义图像
- python - 使用 Beautiful Soup select 或 lxml xpath 从 html 获取 href
- vue.js - 如何使用事件总线正确地将数据从子组件传递到父组件?
- android - 放置意图过滤文件的目录
- python - 如何处理TypeError:必须是str,而不是float
- amazon-web-services - 在 Terraform 中覆盖 STS API 端点时的 SignatureDoesNotMatch
- ios - iOS 应用程序无法检测到它在 CLBeaconRegion 内
- ruby-on-rails - 使用friendly_id gem 避免 RecordNotFound 异常
- python - 在另一个numpy数组中查找数组字符串序列
- spring - 如何在 Spring Session 中实现 HTTP 会话激活监听器