首页 > 解决方案 > 在mysql中查找行的位置

问题描述

我正在想象如何使用查询在 mysql 中实现以下场景。让我展示一下表结构

 id| agentid | value 
  1|  1      | "testing value" 
  2|  1      | "testing value1" 
  3|  2      | "testing value2" 
  4|  2      | "testing value3" 
  5|  1      | "testing value4" 

下面是我想要实现的目标

    id| agentid | value            | position
     1|  10     | "testing value"  |  1
     2|  10     | "testing value1" |  2
     3|  20     | "testing value2" |  1
     4|  20     | "testing value3" |  2
     5|  10     | "testing value4" |  3

让我解释一下,我希望第一行在第一个位置,2 行在 2 个位置等等,但是如果出现新的 agentid,那么它的位置应该是 1 ....

标签: mysqlsql

解决方案


你想要row_number()

select t.*,
       row_number() over (partition by agentid order by id) as position
from t
order by t.id;

自版本 8 发布以来,这已在 MySQL 中可用。

在早期版本中,您可以使用相关子查询或变量。相关子查询很有可能具有不错的性能:

select t.*,
       (select count(*)
        from t t2
        where t2.agentid = t.agentid and t2.id <= t.id
       )
from t;

(agentid, id)你想要一个关于性能的索引。


推荐阅读