我试图使用计数器变量@row
使用单个UPDATE / SELECT语句对桥表上的某些行进行编号。例如:
UPDATE teamrank JOIN (SELECT @row := @row + 1 AS position, name FROM members)
USING(teamID, memberID) SET rank = position
这样的事情是可能的还是我需要创建游标?如果有帮助,我正在使用MySQL 5.
答案 0 :(得分:7)
- 始终初始化用户变量,否则默认为NULL。
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
;
我假设执行团队排名所需的逻辑是团队中个人排名的总和。
同样的技术允许人们执行任何类型的运行总和或计数器,当“组”发生变化时需要重置。
- J Jorgenson -
答案 1 :(得分:0)
如果我理解你的(不完整)查询,这应该会有所帮助:
UPDATE teamrank
JOIN (
SELECT @row := @row + 1 AS position, name
FROM members,
(SELECT @row := 0) AS ObligatoryAlias
) USING(teamID, memberID)
SET rank = position;