mysql - 如何在 SQL 中设置记录相对于组的位置?

标签 mysql sql

我有一系列记录,可以按 group_id 进行分组

记录示例:

╭───╥──────────┬───────────────────╮
│id ║ group_id │ position_in_group │
╞═══╬══════════╪═══════════════════╡
│ 1 ║    2     │        null       │
│ 2 ║    1     │        null       │
│ 3 ║    1     │        null       │
│ 4 ║    1     │        null       │
│ 5 ║    2     │        null       │
│ 6 ║    2     │        null       │
│ 7 ║    3     │        null       │
│ 8 ║    3     │        null       │
│ 9 ║    3     │        null       │
└───╨──────────┴───────────────────┘

我想为每条记录设置position_in_group。如果我GROUP BY group_id,它就是记录在组内的位置。

例如: 在 id 为 1 的组中,id=2 的记录是第一条记录,因此它的 position_in_group 将为 1。

决赛 table 为:

╭───╥──────────┬───────────────────╮
│id ║ group_id │ position_in_group │
╞═══╬══════════╪═══════════════════╡
│ 1 ║    2     │        1          │
│ 2 ║    1     │        1          │
│ 3 ║    1     │        2          │
│ 4 ║    1     │        3          │
│ 5 ║    2     │        2          │
│ 6 ║    2     │        3          │
│ 7 ║    3     │        1          │
│ 8 ║    3     │        2          │
│ 9 ║    3     │        3          │
└───╨──────────┴───────────────────┘

有什么方法可以在 SQL 查询中执行此操作吗?

最佳答案

一种方法是使用变量。在 MySQL 中有点挑战性,但它可能看起来像这样:

set @g := -1;
set @rn := 0;

update t
    set position_in_group = (@rn := if(@g = group_id, @rn + 1,
                                       if(@g := group_id, 1, 1)
                                      )
                            )
    order by group_id, id;

注意:您需要与 update 语句分开初始化变量,因为 MySQL 不支持在同一 update 语句中进行连接和排序。

关于mysql - 如何在 SQL 中设置记录相对于组的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38063315/

相关文章:

php - 在同一 Controller 中的几个方法中重用 mysql 查询代码 - Laravel 5.4

mysql - 如果不存在则插入

sql - 使用 CTE 函数插入语句

mysql - Eloquent where() 语句

sql - 组织.Apache.calcite.runtime.CalciteException : Failed to encode '全国' in character set 'ISO-8859-1'

mysql - 寻找一些聪明的 sql 策略来处理查找表

mysql - 用于在 MySQL DB 中存储标签和 URL 的最佳字符集和排序规则

php - 如何获取每个状态的开始时间和结束时间

mysql - sql在一个查询中获取总计数和过滤计数

mysql - SQL 查询 : Getting the top five tuples based on a value where the value could be the same for some tuples