根据 MySQL 中另一列分组的另一列的顺序更新列

Update columns based on order of another column grouped by another column in MySQL

这是我的 table:

我需要使用更新查询来更新这个 table,这样,在更新查询之后我的 table 应该是:

即)对于 common_id 我需要通过为 common_id.

排序位置来更新从 1 开始的位置

这只是一个示例 table。我的实际 table 有数百万个条目。

如果 id 列设置为自动递增,那么您可以在同一 table

上使用带有连接子句的更新查询
update table1 a
join (
  select a.id,a.common_id,count(*) pos
  from table1 a
  left join table1 b on a.common_id = b.common_id
  and a.id >= b.id
  group by a.id, a.common_id
) b using(id,common_id)
set a.position = b.pos

Demo

如果只是为了选择目的,您可以将其用作

select a.id,a.common_id,count(*) pos
from table1 a
left join table1 b on a.common_id = b.common_id
and a.id >= b.id
group by a.id, a.common_id

Demo

Edit after comment whichever has the minimum position should have position as 1

根据您的评论,您可以根据职位标准进行更新,但这完全取决于 common_id,职位是否唯一意味着每个 common_id

应该有唯一的职位

Select

select a.common_id,a.position,count(*) pos
from table1 a
left join table1 b on a.common_id = b.common_id
and a.position >= b.position
group by a.common_id,a.position
order by a.common_id

Update

update table1 a
join (
  select a.common_id,a.position,count(*) pos
  from table1 a
  left join table1 b on a.common_id = b.common_id
  and a.position >= b.position
  group by a.common_id,a.position
) b using(common_id,position)
set a.position = b.pos