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.
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
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
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.