带WHEN和UPDATE语句的SQL触发器

时间:2019-03-09 12:28:45

标签: mysql sql triggers

我正在编写以下代码,当在“ ecoute”表中插入内容后,该代码应从“ song”表中增加“ 1 likecount”个。 在执行此操作之前,触发器将检查来自新插入的“喜欢”的布尔值是否为“ true”。如果是这样,则UPDATE继续进行。否则,什么也没发生。

CREATE TRIGGER likked AFTER INSERT ON ecoute
FOR EACH ROW
WHEN (NEW.likked)
BEGIN
    UPDATE songs
    SET songs.likecount = songs.likecount +1
    WHERE songs.id = NEW.songid
END

MySQL回答:

#1064 - Syntax error near 'WHEN (NEW.likked)
BEGIN
    UPDATE songs
    SET songs.likecount = songs.like' at line 3

注释: 到目前为止,我一直尝试创建其他JOIN,因为我认为问题是在更新SONGS表时我要求使用NEW表,但是MySQL的答案仍然相同。

2 个答案:

答案 0 :(得分:0)

这是您想要的吗?

DELIMITER $$
CREATE TRIGGER likked AFTER INSERT ON ecoute
FOR EACH ROW
BEGIN
    IF NEW.likked = 1 THEN
        UPDATE songs
            SET songs.likecount = songs.likecount +1
            WHERE songs.id = NEW.songid
    END IF;
END;

DELIMITER ;

答案 1 :(得分:0)

使用IF THEN测试来检查“喜欢”的值

DELIMITER $$
CREATE TRIGGER likked AFTER INSERT ON ecoute
FOR EACH ROW
BEGIN
    IF NEW.likked=1 THEN 
        BEGIN
            UPDATE songs
            SET songs.likecount = songs.likecount +1
            WHERE songs.id = NEW.songid;
        END; 
    END IF; 
END$$
DELIMITER ;