[英]Update columns based on order of another column grouped by another column in MySQL
This is my table: 这是我的桌子:
I need to update this table with an update query such that, after the update query my table should be: 我需要使用更新查询来更新此表,以便在更新查询后,我的表应为:
ie) for a common_id I need to update the position starting from 1 by ordering the position for that common_id. 即)对于common_id,我需要通过订购该common_id的位置来更新从1开始的位置。
This is just a sample table. 这只是一个示例表。 My actual table has millions of entries. 我的实际表有数百万个条目。
If id column is set to auto increment then you can use update query with a join clause on same table 如果将id列设置为自动递增,则可以对同一表使用带有连接子句的更新查询
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
If its just for selection purpose you can use it as 如果仅出于选择目的,则可以将其用作
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 注释后编辑, 无论哪个位置最小,位置都应为1
Following your comment you could update as per position criteria but this totally depends on if common_id,position are unique mean there should be unique position per common_id 在您发表评论之后,您可以按照排名标准进行更新,但这完全取决于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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.