MySQL触发器内的日期差异检查

时间:2014-01-13 19:06:29

标签: mysql date triggers date-format datediff

在我将一些数据插入表格之前的触发器中,我希望它检查我输入的事件的日期差异是否大于或等于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`)

1 个答案:

答案 0 :(得分: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