我正在尝试创建一个触发器来更新插件上另一个表中的行。最后一部分可以工作,但如果没有具有该id的行,我想在添加之前为该id创建一行。
但是我得到了#1064错误:'resource_xpEvents FOR EACH ROW 开始 如果不是EXISTS(从resource_xp'中选择1
DELIMITER $$
CREATE TRIGGER test AFTER INSERT resource_xpEvents FOR EACH ROW
BEGIN
IF NOT EXISTS (SELECT 1 FROM resource_xp WHERE userId = NEW.userId) THEN
INSERT INTO resource_xp (userId)
VALUES (NEW.userId);
END IF;
UPDATE resource_xp
SET xp = xp + new.delta
WHERE userId = new.userId
END $$
DELIMITER ;
答案 0 :(得分:0)
您可以在此处尝试使用MySQL的INSERT ... ON DUPLICATE KEY UPDATE
语法。首先,如果userId
列不是唯一的,请将其设为唯一:
ALTER TABLE resource_xp ADD CONSTRAINT UNIQUE (userId);
然后,不要尝试单独的条件插入和更新语句,而只需执行以下单个语句:
INSERT INTO resource_xp (userId)
VALUES (NEW.userId)
ON DUPLICATE KEY UPDATE xp = xp + NEW.delta
以下是完整建议触发器的代码:
DELIMITER $$
CREATE TRIGGER test AFTER INSERT resource_xpEvents FOR EACH ROW
BEGIN
INSERT INTO resource_xp (userId)
VALUES (NEW.userId)
ON DUPLICATE KEY UPDATE xp = xp + NEW.delta
END $$
DELIMITER ;
答案 1 :(得分:0)
试试这个:
DELIMITER $$
CREATE TRIGGER test AFTER INSERT ON resource_xpEvents FOR EACH ROW
BEGIN
IF NOT EXISTS (SELECT 1 FROM resource_xp WHERE userId = NEW.userId) THEN
INSERT INTO resource_xp (userId)
VALUES (NEW.userId);
END IF;
UPDATE resource_xp
SET xp = xp + new.delta
WHERE userId = new.userId;
END $$
DELIMITER ;
如果你想试验:
DELIMITER $$
CREATE TRIGGER test AFTER INSERT ON resource_xpEvents FOR EACH ROW
BEGIN
REPLACE INTO resource_xp (userId,xp) values (NEW.userId,xp+new.delta);
END $$
DELIMITER ;
更易读,但性能更差。