IF语句在MySQL触发

IF Sentance in MySQL trigger

我正在游戏服务器上建立一个自动排名,我必须通过操纵 MySQL 数据库来做到这一点,这对我来说不是一个强大的知识领域,所以我试图对此有点 hacky .我需要使用 SQL db.

的触发功能
CREATE TRIGGER `ranking_up` AFTER UPDATE ON `highscore` FOR EACH ROW

BEGIN

IF NEW.score >= '10' and <= '100' THEN
    UPDATE department_members
    SET rankID=1 WHERE userID = NEW.userID;
END IF;
IF NEW.score >= '100' and <= '300' THEN
    UPDATE department_members
    SET rankID=2 WHERE userID = NEW.userID;
END IF;
IF NEW.score >= '300' THEN
    UPDATE department_members
    SET rankID=3 WHERE userID = NEW.userID;
END IF;
END

我得到了标准 MySQL #1064,我试着和我的橡皮鸭说话...不起作用这对我来说很有意义,但显然不起作用。

我正在寻找答案,但我也想在这里了解我的错误,我做错了什么?

你无法逃脱 NEW.score >= '10' and >= '100' 你需要重复 new.score NEW.score >= '10' and new.score >= '100' 。如果 new.score 存储为整数...

,您可以更容易地使用 between
delimiter $$
CREATE TRIGGER `ranking_up` AFTER UPDATE ON `highscore` FOR EACH ROW

BEGIN

IF NEW.score between 10 and  99 THEN
    UPDATE department_members
    SET rankID=1 WHERE userID = NEW.userID;
END IF;
IF NEW.score between 100 and 299 THEN
    UPDATE department_members
    SET rankID=2 WHERE userID = NEW.userID;
END IF;
IF NEW.score >= 300 THEN
    UPDATE department_members
    SET rankID=3 WHERE userID = NEW.userID;
END IF;
END $$
delimiter ;

https://www.db-fiddle.com/f/51PoUTCMAuWFoYaAz5ubW7/0

或者您可以在更新语句中完全放弃 ifs 和用例。

delimiter $$
CREATE TRIGGER `ranking_up` AFTER UPDATE ON `highscore` FOR EACH ROW

BEGIN


    UPDATE department_members
    SET RANK = 
     CASE 
        WHEN NEW.score between 10 and  99  THEN 1
        WHEN NEW.score between 100 and 299 THEN 2
        WHEN NEW.score >= 300 THEN 3
     END
     WHERE userID = NEW.userID;
END $$
delimiter ;