I am just new in mysql. I have records like below in carts table
id code
1 100
2 101
3 102
4 100
5 100
6 101
M
Your groups are defined by starting with code = 100
. This is a little tricky. In MySQL 8+, you can use window functions to define the groups and then row_number()
to assign the serial_number
:
select c.*,
row_number() over (partition by grp order by id) as serial_number
from (select c.*,
sum( code = 100 ) over (order by id) as grp
from carts c
) c;
This is much more complicated in earlier versions of MySQL.
You can identify the group using a subquery:
select c.*,
(select count(*)
from carts c2
where c2.id <= c.id and c2.code = 100
) as grp
from carts c;
You can then use variables to get the information you want:
select c.*,
(@rn := if(@g = grp, @rn + 1,
if(@g := grp, 1, 1)
)
) as serial_number
from (select c.*,
(select count(*)
from carts c2
where c2.id <= c.id and c2.code = 100
) as grp
from carts c
order by grp, id
) c cross join
(select @g := -1, @rn := 0) params;