为什么MySQL中的触发器错误?

时间:2017-03-05 08:33:08

标签: mysql database-trigger

我花了很多时间,但我还是无法解决它。

由于某些原因,我想阻止一些相同的插入到数据库。所以我选择使用触发器。也就是说,

    CREATE TRIGGER trigger_card_usage_insert_block 
    BEFORE INSERT ON annual_card_usage_log 
    FOR EACH ROW
    BEGIN

    DECLARE lasttime INT;    -- hold the last insert time

    SELECT
        usage_time INTO lasttime
    FROM
        annual_card_usage_log
    WHERE
        NEW.card_id = card_id
    AND NEW.mch_id = mch_id
    AND NEW.store_id = store_id
    ORDER BY
        usage_time DESC
    LIMIT 1;

    -- only insert when after 300 second
    IF(
        lasttime != NULL
        AND(lasttime + 300 < new.usagetime)
    ) THEN
        INSERT INTO annual_card_usage_log(
            card_id ,
            mch_id ,
            store_id ,
            usage_time
        )
    VALUES
        (
            NEW.card_id ,
            NEW.mch_id ,
            NEW.store_id ,
            NEW.usage_time
        );
    END
    IF;

    END$

这是创建代码。以下是表格,

CREATE TABLE `annual_card_usage_log` (
      `usage_id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
      `card_id` int(10) unsigned NOT NULL COMMENT '',
      `mch_id` int(10) unsigned NOT NULL COMMENT '',
      `store_id` int(10) DEFAULT NULL,
      `usage_time` int(10) NOT NULL COMMENT '',
      PRIMARY KEY (`usage_id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

可悲的是我无法创建触发器,这似乎是错误的。你能告诉我为什么吗?哪个代码错了。

我使用名为Sequel Pro的mysql客户端,当我运行sql时,我收到一条错误消息“您的SQL语法中有错误;请查看与您的MySQL服务器版本对应的手册,以便在附近使用正确的语法''第6行执行停止!“我现在不是原因。

1 个答案:

答案 0 :(得分:1)

感谢@anatol我解决了它。我改变了方向。我将值设置为无效数据。然后创建一个作业以删除无效数据。

触发器无法插入到同一个表中,因为它会导致无限循环,就像@anatol指出的那样。

    DELIMITER $$
    CREATE TRIGGER triger_card_usage_insert_block BEFORE INSERT ON annual_card_usage_log FOR EACH ROW
    BEGIN

    DECLARE lasttime INT(10) ;
    SET lasttime =(
        SELECT
            usage_time
        FROM
            annual_card_usage_log
        WHERE
            NEW.card_id = card_id
        AND NEW.mch_id = mch_id
        AND NEW.store_id = store_id
        ORDER BY
            usage_time DESC
        LIMIT 1
    ) ;
    IF (lasttime + 300 > new.usage_time) THEN
    SET new.new_card_id = new.card_id;
    SET new.card_id = 0 ;
    END
    IF ;
    END$$
    DELIMITER ;