Dine grupper defineres ved at starte med code = 100
. Det her er lidt tricky. I MySQL 8+ kan du bruge vinduesfunktioner til at definere grupperne og derefter row_number()
for at tildele 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;
Dette er meget mere kompliceret i tidligere versioner af MySQL.
Du kan identificere gruppen ved hjælp af en underforespørgsel:
select c.*,
(select count(*)
from carts c2
where c2.id <= c.id and c2.code = 100
) as grp
from carts c;
Du kan derefter bruge variabler til at få den information, du ønsker:
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;