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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了根据MySQL中另一列分组的另一列的顺序更新列相关的知识,希望对你有一定的参考价值。

这是我的表:

enter image description here

我需要使用更新查询更新此表,以便在更新查询后我的表应该是:

enter image description here

即)对于common_id,我需要通过命令该common_id的位置来更新从1开始的位置。

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

答案

如果id列设置为自动递增,则可以在同一个表上使用带有join子句的update query

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

在评论后编辑最小位置的位置应为1

根据您的评论,您可以根据位置标准进行更新,但这完全取决于common_id,position是否唯一意味着每个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

以上是关于根据MySQL中另一列分组的另一列的顺序更新列的主要内容,如果未能解决你的问题,请参考以下文章

使用同一表中另一列的键更新 mysql 列

根据不同数据类型的另一列设置一列的默认值

如何根据火花DataFrame中另一列的值更改列的值

根据另一列的另一个值和/或另一行中的同一列更新设置值:-ORA 1427

根据火花数据框中另一列的值查找列的最大值?

如何根据R中另一列的日期(月/日/年)计算列的年/月平均值、最大值、最小值等