2

This is my table:

enter image description here

I need to update this table with an update query such that, after the update query my table should be:

enter image description here

i.e) 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.

James Z
  • 12,209
  • 10
  • 24
  • 44
Surya
  • 2,429
  • 1
  • 21
  • 42

1 Answers1

4

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

Demo

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

Demo

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

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
M Khalid Junaid
  • 63,861
  • 10
  • 90
  • 118
  • This is really good, but it just updates the position based on the id. i.e) whichever is coming first for a common id gets position as 1, but whichever has the minimum position should have position as 1. For the example I have for common_id=4, the update query you have given wont work. – Surya Dec 22 '17 at 11:41
  • @SuryaPandian check the updated answer as per your needs – M Khalid Junaid Dec 22 '17 at 11:50