且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何根据MySQL中的组添加自动增量ID

更新时间:2023-02-20 23:12:09

尝试一下:

update yourtable t1
join (
    select
          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

此处演示

Edited:

如果要插入新行,则必须这样做:

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'