gpt4 book ai didi

mysql - 比较触发器 MYSQL 中的日期

转载 作者:行者123 更新时间:2023-11-29 09:32:29 26 4
gpt4 key购买 nike

我正在创建一个“插入之前”触发器。我需要做的是比较新行是否与最后一行有 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;;

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

插入示例:

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

插入成功

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

插入正常,它不应该发生...

有什么帮助吗?

提前致谢!! :)

最佳答案

如果 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

关于mysql - 比较触发器 MYSQL 中的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58390020/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com