我有一系列记录,可以按 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/