比较触发器中的日期 MYSQL

Comparing dates in a trigger MYSQL

我正在创建一个 "before insert" 触发器。我需要做的是比较新行与最后一行是否有 60 秒(或 1 分钟)的差异(考虑时间)。

我的代码如下:

    CREATE TRIGGER before_insert_detection 
    BEFORE INSERT ON detection
    FOR EACH ROW
    BEGIN

         Declare oldDate date;
         Declare newDate date;
         Declare timediff int;

         SELECT DATE_DETECTION into oldDate
         FROM DETECTION ORDER BY DATE_DETECTION desc limit 1;

         SET newDate = NEW.DATE_DETECTION;
         SET timediff = (TIMESTAMPDIFF(SECOND, oldDate, newDate)) < 60;

         IF timediff = 1 
            THEN SIGNAL SQLSTATE '02000' SET MESSAGE_TEXT = "Same detection less than a minute 
            ago";END IF; 
     END;;

因此,如果两个日期之间的差异小于一分钟,timediff 必须为 1,并且应该引发消息。但这永远不会发生...无论时间如何,都不会插入任何行...

插入示例:

INSERT INTO DETECTION VALUES (1, '2019-10-15 12:00:01');

插入成功

INSERT INTO DETECTION VALUES (2, '2019-10-15 12:00:20');

插入OK,应该不会发生...

有什么帮助吗?

提前致谢!! :)

如果 olddate 和 newdate 定义为日期时间,我无法重现您的问题。

 drop trigger if exists t;

drop table if exists t;
create table t(id int auto_increment primary key,date_detection datetime); 
delimiter $$
CREATE TRIGGER t 
    BEFORE INSERT ON t
    FOR EACH ROW
    BEGIN

         Declare oldDate datetime;
         Declare newDate datetime;
         Declare timediff int;

         SELECT DATE_DETECTION into oldDate
         FROM t ORDER BY DATE_DETECTION desc limit 1;

         SET newDate = NEW.DATE_DETECTION;
         SET timediff = (TIMESTAMPDIFF(SECOND, oldDate, newDate)) < 60;

         IF timediff = 1  THEN 
                SIGNAL SQLSTATE '02000' SET MESSAGE_TEXT = 'Same detection less than a minute ago';

            END IF; 
     END $$

delimiter ;

MariaDB [sandbox]> set @olddate = '2019-10-15 12:00:01';
Query OK, 0 rows affected (0.00 sec)

MariaDB [sandbox]>
MariaDB [sandbox]> insert into t (date_detection) values (@olddate);
ERROR 1643 (02000): Same detection less than a minute ago
MariaDB [sandbox]> set @newdate = '2019-10-15 12:00:20';
Query OK, 0 rows affected (0.01 sec)

MariaDB [sandbox]> insert into t (date_detection) values (@newdate);
ERROR 1643 (02000): Same detection less than a minute ago