I am trying to number some rows on a bridge table with a single UPDATE/SELECT statement using a counter variable @row. For example:
UPDATE teamrank JOIN (SELECT @row := @row + 1 AS position, name FROM members)
USING(teamID, memberID) SET rank = position
Is something like this possible or do I need to create a cursor? If it helps, I am using MySQL 5.
-- ALWAYS initialize user variables, they default to NULL otherwise.
SET @prevID:=@runSum:=0;
UPDATE teamrank t -- one row per team?
JOIN members m USING ( teamID ) -- multiple rows per team?
SET rank =
IF( @prevID != m.teamID, /* Capture when a teamIDs changes */
( @runSum := m.rank ) + ((@prevID := m.teamID)*0), /* reset both @runSum and @prevTeam */
( @runSum := @runSum + m.rank) /* increment running sum */
)
-- It is important to have proper sequencing, so to reset @runSum when a teamID changes.
ORDER BY t.teamID
;
I've made an assumptions that the logic needed to perform a team rank, is the sum of the ranks for individuals within a team.
This same technique allows one to perform any kind of running sum or counter that needs to be reset when a 'group' changes.
-- J Jorgenson --
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With