首页 > 解决方案 > 限制数据库表只有一个未来日期记录

问题描述

我们的项目要求一张表上只允许有一个未来日期的记录。每个表都使用开始日期和结束日期维护记录版本。下面的屏幕截图中附有一个示例场景。(假设今天的日期是 2019 年 3 月 7 日)

在此处输入图像描述

那么,如何限制数据库表具有多个未来日期记录。是否有任何约束或触发器有助于从数据库本身进行验证?(我正在使用 MySQL db)

标签: mysqldatabasedatabase-design

解决方案


例如,一种简单的方法可能是在触发器中用 null 覆盖结束日期

drop trigger if exists t;
delimiter $$
create trigger t before insert on t
for each row 
begin
    declare cnt int default 0;
    select count(*) into cnt from t where end_date > date(now());
    if cnt > 0 then
        set new.end_date = null;
    end if;
end $$

delimiter ;


insert into t (designation,end_date) values 
('a','2019-03-07'),('a','2019-03-07'),('a','2019-04-07'),('a','2019-04-07'),
('b','2019-04-07');

select * from t;

+----+-------------+------------+
| id | designation | end_date   |
+----+-------------+------------+
|  1 | a           | 2019-03-07 |
|  2 | a           | 2019-03-07 |
|  3 | a           | 2019-04-07 |
|  4 | a           | NULL       |
|  5 | b           | NULL       |
+----+-------------+------------+
5 rows in set (0.00 sec)

如果您愿意,可以使用 if exists 测试稍微调整代码。


推荐阅读