简体   繁体   中英

Mysql Update Self Join , Increment Column value based on Group

I have a table whose structure is similar to below .

+----+---------------+-------+
| id | group | value |
+----+---------------+-------+
| 1 | g1 | null |
| 2 | g1 | null |
| 3 | g2 | null |
| 4 | g2 | null |
| 5 | g2 | null |
| 6 | g3 | null |
| 7 | g3 | null |
| 8 | g4 | null |
| 9 | g4 | null |
+----+---------------+-------+

I need to update the value column so that the table looks like

+----+---------------+-------+
| id | group | value |
+----+---------------+-------+
| 1 | g1 | 1 |
| 2 | g1 | 2 |
| 3 | g2 | 1 |
| 4 | g2 | 2 |
| 5 | g2 | 3 |
| 6 | g3 | 1 |
| 7 | g3 | 2 |
| 8 | g4 | 1 |
| 9 | g4 | 2 |
+----+---------------+-------+

Basically i am increment the value column based on the group column .

You can try below - using self join

DEMO

update tablename t
join
(select b.id,b.groupname,count(b.id) as val from t1 a
join t1 b on a.groupname=b.groupname
and a.id<=b.id
group by b.id,b.groupname
)d on t.id=d.id
set value=val

OR

you can use row_number() function if your mysql version is 8.0+

update tablename t
join
(
  select *, row_number() over(partition by groupname order by id) as rn from t1 
)d on t.id=d.id
set value=rn

Please try this I hope this is useful for you

Update A 
set value = _val
from @tblName As A
INNER JOIN (
SELECT id,Row_NUMBER() over(partition by [group] order by id) as _val  from  @tblName
)As B ON A.id = B.id

In older versions of MySQL, variables are the simplest method:

set @rn := 0;
set @grp := '';

update t
    set value = (@rn := if(@grp = t.group, @rn + 1,
                           if(@grp := t.group, 1, 1)
                          )
                )
    order by group, id;

In MySQL 8.0, use fa06's second query.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM