开发者

Reset SQL variable inside SELECT statement

I am trying to numbe开发者_如何学运维r 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 I understand your (incomplete) query properly, this should help:

UPDATE teamrank 
   JOIN (
      SELECT @row := @row + 1 AS position, name 
         FROM members, 
            (SELECT @row := 0) AS ObligatoryAlias
   ) USING(teamID, memberID) 
SET rank = position;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜