Heider Kumar Heider Kumar - 1 year ago 88
MySQL Question

How to add auto increment id according to a group in mysql

Here is the format of the table:

indexer group name id
1 abc a
2 abc b
3 xyz c
4 abc e
5 xyz d

Now i want it to be like,

indexer group name id
1 abc a 1
2 abc b 2
3 xyz c 1
4 abc e 3
5 xyz d 2

"id" should auto increment according to "group"

Answer Source

Try this:

update yourtable t1
join (
          tt.indexer, @rowno := if(@grp = `group`, @rowno + 1, 1) as id, @grp := `group`
    from (select * from yourtable order by `group`, indexer) tt
    cross join (select @rowno := 0, @grp := null) t
) t2
on t1.indexer = t2.indexer
set t1.id = t2.id

Demo Here


If you want to insert a new row, you have to do it like this:

insert into yourtable
select '$indexer', '$group', '$name', coalesce(max(id), 0) + 1
from yourtable
where name = '$name'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download