2

我有一个带有 id 和值的表。如何按其值按顺序对表中的元素进行排名?我想做的是:

SELECT id FROM table ORDER BY value DESC

我希望它告诉我例如 id=4 的位置

非常感谢您的回答!

4

2 回答 2

2

MySQL 没有解析函数,所以你必须使用用户变量

SELECT   @r:=@r+1 AS rank, id
FROM     table, (SELECT @r:=0) init
ORDER BY value DESC

要获取特定记录的排名,请将其包装在外部查询中:

SELECT rank FROM (
  SELECT   @r:=@r+1 AS rank, id
  FROM     table, (SELECT @r:=0) init
  ORDER BY value DESC
) t WHERE id = 4

为了避免 MySQL 不必要地计算表中每条记录的排名,您可以添加一个过滤器:

SELECT rank FROM (
  SELECT   @r:=@r+1 AS rank, table.id
  FROM     table,
           (SELECT value FROM table WHERE id=4) t,
           (SELECT @r:=0) init
  WHERE    table.value >= t.value
  ORDER BY table.value DESC
) t WHERE id = 4
于 2012-10-18T16:44:34.410 回答
1

Eggyal 的解决方案不是 a rank,而是 a row_number(这些实际上是有意义的,因为它们是 SQL 标准的一部分)。

我认为以下dense_rank在 MySQL 中做了一个:

SELECT   @r:=@r+1 AS rank, id
FROM     (select id, count(*) as cnt
          from table t
          group by id
         ),
         (SELECT @r:=0) init
ORDER BY value DESC

Arank有点难。. . 我认为以下将起作用:

SELECT   @r:=@r+1-offset AS rank, id
FROM     (select id, count(*) as cnt
          from table t
          group by id
         ),
         (SELECT @r:=0, count(*)-1 as offset
          from table t
          group by id
          order by count(*) desc
          limit 1
         ) init
ORDER BY value DESC
于 2012-10-18T17:45:29.310 回答