这是我的 table :
我需要使用更新查询来更新此表,以便在更新查询之后我的表应该是:
即)对于 common_id,我需要通过对该 common_id 的位置进行排序来更新从 1 开始的位置。
这只是一个示例表。我的实际表有数百万个条目。
最佳答案
如果 id 列设置为自动递增,那么您可以在同一个表上使用带有 join 子句的更新查询
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
如果只是为了选择目的,您可以将其用作
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
Edit after comment whichever has the minimum position should have position as 1
根据您的评论,您可以根据位置标准进行更新,但这完全取决于 common_id,position 是否唯一,意味着每个 common_id 应该有唯一的位置
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 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
关于mysql - 根据 MySQL 中另一列分组的另一列的顺序更新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47940461/