使用MySQL,如何选择某一特定行的查询结果排名?
今天我花了很多时间尝试各种事情,但似乎都不起作用。 这是我的情况,我希望能够根据特定排序行中的 ID 选择行的排名
例如,如果我的查询类似于:
SELECT id, name FROM people ORDER BY name ASC
结果如下:
id name 3 Andrew 1 Bob 5 Joe 4 John 2 Steve
我想获得排名(什么row 它最终出现在结果中),而不返回所有行并循环抛出它们,直到我到达我想要的行(在 PHP 中)。
例如,我想选择“Steve”的“排名”,以便在本例中返回 5(不是他的 id,而是上面查询中他姓名的“排名”)。
同样,我希望能够选择 ID 为 1 的任何行的排名。对于此示例,我希望返回 2 的“排名”(因为在结果行中,ID 为1)没有别的。
我已经尽可能多地用谷歌搜索不同的结果...要么对较大的表的查询非常慢,要么必须创建各种临时表和用户变量(前者我真的很想避免,后者我想我可以忍受)。
任何帮助或见解将不胜感激。
I've spent quite a lot of time today trying various things, but none of them seem to work. Here's my situation, I'd like to be able to select the rank of a row based on it's ID from a specifically sorted row
For example, if my query is something like:
SELECT id, name FROM people ORDER BY name ASC
with results like:
id name 3 Andrew 1 Bob 5 Joe 4 John 2 Steve
I would like to get the rank (what row it ends up in the results) without returning all the rows and looping throw them until I get to the one I want (in PHP).
For example, I'd like to select the 'rank' of 'Steve' so that it returns -- in this case -- 5 (not his id, but the 'rank' of his name in the above query).
Similarly, I'd like to be able to select the rank of whatever row has the ID of 1. For this example, I'd like to return a 'rank' of 2 (because that's in what result row there is an ID of 1) and nothing else.
I've Google'd as much as I could with varying results... either having really slow queries for larger tables or having to create all sorts of temporary tables and user variables (the former I'd REALLY like to avoid, the latter I suppose I can live with).
Any help or insight would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我尝试这段代码...可能会帮助其他人
我从用户那里获取结果,并上传用户个人资料图片表并加入它,而不是在我计算用户积分并对它们进行排序之后。
最后检查并添加行号以对用户进行排名...
享受它。
谢谢
I try to this code... may help other
I am getting result from users and upload table for user profile pic and join it than after i am calculating user points and sorting on them.
At last am checking and adding row number for ranking for users...
Injoy it.
thanks
来自artfulsoftware:
from artfulsoftware:
像这样的东西吗?
如果您想通过 ID,只需更改 where 子句即可。
Something like this?
If you want to go by the ID, just alter the where clause.
尝试这个:
Try this: