Mysql
 sql >> Base de données >  >> RDS >> Mysql

Comment ajouter un identifiant d'incrémentation automatique en fonction d'un groupe dans mysql

Essayez ceci :

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

Démo ici

Modifié :

Si vous voulez insérer une nouvelle ligne, vous devez le faire comme ceci :

insert into yourtable
select '$indexer', '$group', '$name', coalesce(max(id), 0) + 1
from yourtable
where name = '$name'