mysql - 在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 ....
解决方案
你想要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)
你想要一个关于性能的索引。
推荐阅读
- discord.py - 删除 Discord Markdown
- python - 带有破折号的 CSV 文件的数据可视化
- php - 使用密码验证删除帐户
- angular - Angular 11 - 用不同的路径调用相同的组件
- javascript - 如何在 Javascript 中引用 Wordpress 目录常量
- unity3d - 如何添加 App Store 产品页面横幅
- javascript - shufflePlaylist 应该如何在 javascript 中工作?
- authentication - 如何添加自定义身份验证类来实现?
- heroku - 我很好奇 Heroku Dyno 小时的概念
- php - 来自远程 JSON API 端点的 PhpStorm 中的代码完成