简体   繁体   English

如何从 MySQL SELECT 语句中获取排名位置

[英]How to get rank position from MySQL SELECT statement

I'm trying to get the rank value of a MySQL SELECT statement, (MySQL is not something I'm too familiar with).我正在尝试获取 MySQL SELECT 语句的排名值,(MySQL 不是我太熟悉的东西)。

This query give me the correct results I am looking for in the correct order (by greater number of stats), but I need to get a particular value from the results.此查询以正确的顺序(通过更多的统计数据)为我提供了我正在寻找的正确结果,但我需要从结果中获取特定值。

SELECT id, stats,
@curRank := @curRank + 1 AS rank
FROM statistics.web_stats p, (SELECT @curRank := 0) r 
ORDER BY stats DESC;

Gives me this expected result:给了我这个预期的结果:

id,stats,rank
999,291,1
1137,82,2
1084,79,3
1111,60,4
1097,55,5
1094,51,6
1109,50,7
1112,49,8
1154,44,9
1082,36,10

What I need to do it get the rank value of any particular id, for example, in my PHP code, how would I find the rank position of id 1111 (to return the rank value of '4')?我需要做的是获取任何特定 id 的排名值,例如,在我的 PHP 代码中,我将如何找到 id 1111 的排名位置(返回 '4' 的排名值)?

I'm stuck with hoe to further extract values from the results.我坚持使用锄头进一步从结果中提取值。 Do I need to save them somehow, or can I further expand the MySQL query?我需要以某种方式保存它们,还是可以进一步扩展 MySQL 查询?

Thanks.谢谢。

You can use any one of the solutions:您可以使用以下任何一种解决方案:

  1. You need to use a subquery to maintain rank position.您需要使用子查询来维护排名位置。

This will give you a result whose rank is 4:这会给你一个等级为 4 的结果:

SELECT * 
FROM
(
    SELECT id, stats,
    @curRank := @curRank + 1 AS rank
    FROM statistics.web_stats p, (SELECT @curRank := 0) r 
    ORDER BY stats DESC
) AS stat
WHERE rank = 4;
  1. You can even use LIMIT OFFSET to query as they are already in order:你甚至可以使用LIMIT OFFSET来查询,因为它们已经是有序的:
    SELECT id, stats,
    @curRank := @curRank + 1 AS rank
    FROM statistics.web_stats p, (SELECT @curRank := 0) r 
    ORDER BY stats DESC 
    LIMIT 4, 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM