如何使用mysql获得位置

时间:2016-03-17 21:29:05

标签: php mysql

我有一张这样的表:

Name         Total
Foo          7
FoBarr       2
Fobarr2      2
Foobar       5
FBar         8
FBar2        8
FBar3        8
FbarL        9

我真正想要的不是获得这样的位置的方法:

Name    Total    Position
FoBarr     2        1st
FoBarr2    2        1st
Foobar     5        3rd     // notice that there is no 2nd position
Foo        7        4th
FBar       8        5th
FBar2      8        5th
FBar3      8        5th
FbarL      9        8th    // notice that there is no 6th and 7th...

我很感激SQL查询解决方案,虽然我也在使用php应用程序。

我已经搜索过了,我相信这个问题并不完全属于等级函数,因为如果存在关系,这个位置不会像顺序一样继续下去。

感谢。

1 个答案:

答案 0 :(得分:1)

Oooook,所以,如果这不是一个实际的重复,那么让我详细说明我之前链接的答案:

SET @prev_value = NULL;
SET @count = 0;
SET @rank_count = 0;
SELECT Name, total,
@count := @count + 1 as RowNumber,
CASE
    WHEN @prev_value = total THEN @rank_count
    WHEN @prev_value := total THEN @rank_count := @count
END AS Position
FROM rank_table
ORDER BY total

你要做的是拿2个计数器,1对每一行增加1,另一个将保持排名值,当值改变时重置为第一个计数器。

有关SQL小提琴的信息,请参阅here