Mysql程序增量变量

时间:2013-12-03 14:16:10

标签: mysql procedure

我正在尝试使用存储时间在表中获得用户等级。

RAW SQL查询工作正常但我无法使其作为过程工作。

SET @rownum := 0;
SELECT rank, user_id, best_time
FROM (
  SELECT @rownum := @rownum +1 AS rank,id, best_time, user_id
  FROM user_round WHERE round_id=1 ORDER BY best_time ASC
) AS result WHERE user_id = 1 

我尝试过程:

BEGIN
 DECLARE variable INT DEFAULT 0;
 SELECT rank,best_time, user_id
 FROM (
  SELECT SET variable=variable+1 AS rank, best_time, user_id
  FROM database.user_round WHERE round_id=1 ORDER BY best_time ASC
 ) AS result WHERE user_id = 1;
END

1 个答案:

答案 0 :(得分:3)

您需要继续使用9.4. User-Defined Variables,而不是13.6.4.1. Local Variable DECLARE Syntax

BEGIN
    -- DECLARE variable INT DEFAULT 0;
    SELECT rank, best_time, user_id
    FROM (
        -- SELECT SET variable = variable + 1 AS rank, best_time, user_id
        SELECT @variable := @variable + 1 AS rank, best_time, user_id
        FROM database.user_round, (SELECT @variable := 0) init
        WHERE round_id = 1
        ORDER BY best_time ASC
    ) AS result
    WHERE user_id = 1;
END