【问题标题】:MySQL date difference check within a trigger触发器内的 MySQL 日期差异检查
【发布时间】:2014-02-01 16:07:54
【问题描述】:

在我将一些数据插入表之前的触发器中,我希望它检查我输入的事件日期的差异是否大于或等于 1 天。一个俱乐部每天只能举办一场活动。

示例故事

如果数据库中已经有2014-01-01 19:00:00 日期并且我正在尝试插入另一条日期为2014-01-01 的记录(小时无关紧要),它不应该允许

触发器的部分代码

DECLARE k INT DEFAULT 0;

/* This is where I get the error, ABS is to make it always positive to go through  
checking, so that it wont matter whether the NEW date is before or after */

SELECT ABS(DATEDIFF(DATE_FORMAT(`performance_date`, '\'%Y-%m-%d %H:%i:%s\''), 
DATE_FORMAT(NEW.`performance_date`, '\'%Y-%m-%d %H:%i:%s\''))) INTO k;

/* Below code is out of scope for this question */

IF k = 0 THEN
    SIGNAL SQLSTATE '58005'
    SET MESSAGE_TEXT = 'Wrong! Only 1 performance in 1 club is allowed per day! Change your date, or club!';
END IF;

错误代码:1054。“字段列表”中的未知列“performance_date”

我尝试了一些简单的方法:

...DATEDIFF(`performance_date`, NEW.`performance_date`)

【问题讨论】:

    标签: mysql date triggers date-format datediff


    【解决方案1】:

    您可以使用SELECT ... INTO var_list 查询COUNT 数据库中有多少条目与您的时间相匹配:

    我假设您的意思是每天一个条目,并且我假设 performance_date 列是 DATETIMETIMESTAMP 类型。

    DECLARE k INT DEFAULT 0;
    
    /* Count number of performances occurring on the same date as the 
       performance being inserted */
    SELECT COUNT(*)
    FROM tbl
    WHERE performance_date
    BETWEEN DATE(NEW.`performance_date`)
    AND DATE(DATE_ADD(NEW.`performance_date`, INTERVAL 1 DAY))
    INTO k;
    
    /* If k is not 0, error as there is already a performance */
    IF k != 0 THEN
        SIGNAL SQLSTATE '58005'
        SET MESSAGE_TEXT = 'Wrong! Only 1 performance in 1 club is allowed per day! Change your date, or club!';
    END IF;
    

    为清楚起见,如果您有一个以 performance_date 为 2014-01-01 19:00:00 的表演,并且您插入了一个日期为 2014-01-01 08:30:00 的新表演(例如),那么上面的代码将运行这个查询,它会返回一个 COUNT 的 1,这将导致触发器给出那个错误:

    SELECT COUNT(*)
    FROM tbl
    WHERE performance_date
    BETWEEN DATE("2014-01-01 08:30:00") AND DATE(DATE_ADD("2014-01-01 08:30:00", INTERVAL 1 DAY))
    # The line above will become:
    # BETWEEN "2014-01-01" AND "2014-01-02"
    INTO k
    

    【讨论】:

    • 如果performance_date 介于NEW.performance_dateNEW.performance_date - 1 之间呢?
    • 在问题中使用您的示例,NEW.performance_date - 1 将等于2013-12-31 19:00:00,因此从2013-12-31 19:00:002013-12-31 23:59:59 的任何内容都将在不同的日子(我认为没问题)和一切从 2014-01-01 00:00:002014-01-01 23:59:59 将匹配查询,因此被标记为“在您尝试添加新事件的当天已经有一个事件”。
    • 你的意思是演出之间必须有24小时?不只是一天不能举办两场活动吗?
    • 不用担心,不,我使用 sqlfiddle.com 来检查 DATE_ADD() 是否正常工作,但只是用了我的大脑 :)
    • 按预期工作。谢谢。
    猜你喜欢
    • 2017-02-28
    • 1970-01-01
    • 2017-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-21
    • 1970-01-01
    相关资源
    最近更新 更多