【问题标题】:I can't get specific row's postition in table using order by in MySQL我无法在 MySQL 中使用 order by 获取表中的特定行位置
【发布时间】:2021-02-17 06:11:52
【问题描述】:

我想使用“order by”操作获取 MySQL 表中特定行的位置。 假设我有这张桌子:

现在我想按 user_points(升序)排序它们并在这里获取 Ann 的位置。我想要的输出是'3'。我正在尝试这样做,但没有结果......如果有人知道如何做到这一点,我将不胜感激。

【问题讨论】:

  • 哪个 MySQL 版本?
  • xampp,它是 10.4.11-MariaDB - mariadb.org 二进制发行版

标签: mysql sql sql-order-by


【解决方案1】:

一种方法是:

select count(*) + 1
from t
where t.user_points < (select t2.user_points
                       from t t2
                       where t2.name = 'Ann'
                      );

这相当于窗口函数rank()

select t.*, rnk
from (select t.*, rank() over (order by score) as rnk
      from t
     ) t
where name = 'Ann';

但是有了正确的索引,第一个版本可能会快一点。

【讨论】:

  • 我会检查并提供反馈:D
猜你喜欢
  • 2011-04-06
  • 2020-09-21
  • 1970-01-01
  • 2021-12-04
  • 2015-09-22
  • 2012-09-02
  • 2015-03-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多