我正在创建一个“插入前”触发器。我需要做的是比较新行是否与最后一行相差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,并且该消息将引发。但这永远不会发生...无论何时,所有行都被插入...
有帮助吗?
谢谢!! :)
我无法重现您的问题
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 date;
Declare newDate date;
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 09:13:00';
Query OK, 0 rows affected (0.00 sec)
MariaDB [sandbox]> set @newdate = '2019-10-15 09:13:15';
Query OK, 0 rows affected (0.00 sec)
MariaDB [sandbox]> insert into t (date_detection) values (@olddate);
Query OK, 1 row affected (0.01 sec)
MariaDB [sandbox]> insert into t (date_detection) values (@newdate);
ERROR 1643 (02000): Same detection less than a minute
ago