MySQL程序忽略LEAVE语句?

时间:2015-07-18 18:53:27

标签: mysql stored-procedures

这是程序:

main:BEGIN

# make sure a game isnt already running
SELECT COUNT(*), `winner` INTO @running, @winner
    FROM `games`
    WHERE `winner` IS NULL;

IF @running != 0 THEN
    SELECT 0 as 'success', @running as 'running', @winner as 'winner';
    LEAVE main;
END IF;

SELECT `id` INTO @lastGame 
    FROM `games` 
    WHERE 1
    ORDER BY `id` DESC
    LIMIT 1;

SELECT `charity_id` INTO @lastWinner
    FROM `runners` 
    WHERE `game_id` = @lastGame
    ORDER BY `donated` DESC
    LIMIT 1;


INSERT INTO `games` (`target`)
    VALUES (_target);

SET @gameId = LAST_INSERT_ID();

INSERT INTO `runners` (`game_id`, `charity_id`)
    VALUES (@gameId, @lastWinner);

SET @runners = 1;

WHILE @runners < 5 DO
    SELECT `id` INTO @rand FROM `charities` 
        WHERE `id` != @lastWinner 
        ORDER BY rand() LIMIT 1;

    INSERT IGNORE INTO `runners` (`game_id`, `charity_id`)
        VALUES (@gameId, @rand);

    SELECT COUNT(*) INTO @runners 
        FROM `runners`
        WHERE `game_id` = @gameId;
END WHILE;

SELECT 1 as 'success', @gameId as 'gameId';

END

当我运行此示例时,games表中存在winner = 3的单个条目,返回的结果为:

success: 0, running: 1, winner: NULL

IF @running != 0 THEN ... END IF;块之后的所有代码也被执行了!新游戏会添加到games中,并会在表格中添加五个新runners

1)如果winner = 1那么为什么@running == 1?

2)如果那个IF ... END IF;块正在运行,为什么它不会占用主块,而是继续执行其余的代码?

1 个答案:

答案 0 :(得分:0)

创建了一个小测试:LEAVE无法正常工作(因此技术上mysql会做它应该做的事情)。

这段代码很有意思:

SELECT COUNT(*), `winner` INTO @running, @winner
FROM `games`
WHERE `winner` IS NULL;

这将返回 @ running = 0 @ winner = NULL 。使用 @ running = 0 ,您的代码的其余部分才会运行。 @ running = 1(以及您的整个日志记录行)来自哪里是模糊的。最好的机会是:通过删除程序并重新创建它来确定这是您正在使用的代码而不是其他(旧的?)版本。