所以我有一个例程(伪代码):
$rows = SELECT DISTINCT a, b FROM t1;
foreach($rows as $row) {
SET @i = 0;
UPDATE t1 SET c_index = @i := (@i+1)
WHERE a = $row[a] and b = $row[b] ORDER BY c DESC;
}
关键是按行的排序方式对行子集进行编号。工作正常,但这是更新运行数千次,所以很慢。为了加快速度,我想把它放在一个存储过程中。
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE vA, vB, i INT;
DECLARE cur1 CURSOR FOR
SELECT DISTINCT a, b
FROM t1 WHERE ...;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur1;
WHILE done = 0 DO
FETCH cur1 INTO vA, vB;
IF done = 0 THEN
SET i=0;
UPDATE t1
SET c_index = i:= (i+1)
WHERE a = vA AND b = vB
ORDER BY c DESC;
END IF;
END WHILE;
CLOSE cur1;
END
但是,在创建上述过程时,MySQL 说“i := ...”处存在语法错误。如果我为“i”使用会话变量,它可以工作(@i)。在存储过程中使用会话变量不是很优雅。如何在不使用“i”的会话变量的情况下修复上述存储过程?