MySQL - 强制新记录字段值大于先前记录字段值的约束

时间:2016-10-25 01:16:57

标签: mysql sql schema

我正在尝试创建一个数据库模式,强制特定表中的记录确认下面的示例数据结构所代表的格式...

+--------------+--------+---------------+-----------------+
| EQUIPMENT_ID | CML_ID | INSPECTION_ID | INSPECTION_DATE |
+--------------+--------+---------------+-----------------+
| B1001-V001   |      1 |             1 | 2010-01-01      |
| B1001-V001   |      1 |             2 | 2011-01-01      |
| B1001-V001   |      1 |             3 | 2012-01-01      |
| B1001-V001   |      1 |             4 | 2013-01-01      |
| B1001-V001   |      1 |             5 | 2014-01-01      |
| B1001-V001   |      1 |             6 | 2015-01-01      |
| B1001-V001   |      1 |             7 | 2016-01-01      |
| B1001-V001   |      1 |             8 | 2017-01-01      |
| B1001-V001   |      1 |             9 | 2018-01-01      |
| B1001-V001   |      1 |            10 | 2019-01-01      |
| B1001-V001   |      2 |             1 | 2010-01-01      |
| B1001-V001   |      2 |             2 | 2011-01-01      |
| B1001-V001   |      2 |             3 | 2012-01-01      |
| B1001-V001   |      2 |             4 | 2013-01-01      |
| B1001-V001   |      2 |             5 | 2014-01-01      |
| B1001-V001   |      2 |             6 | 2015-01-01      |
| B1001-V001   |      2 |             7 | 2016-01-01      |
| B1001-V001   |      2 |             8 | 2017-01-01      |
| B1001-V001   |      2 |             9 | 2018-01-01      |
| B1001-V001   |      2 |            10 | 2019-01-01      |
+--------------+--------+---------------+-----------------+

基本上我想强制执行最大的INSPECTION_ID(AUTO INCREMENTED)对于EQUIPMENT_ID和CML_ID的特定组合始终具有最大的INSPECTION_DATE(由用户手动输入)。

在外行人的条款中,我想确保用户始终按时间顺序进行检查。

我可以采取某种规则,约束或架构设计来强制执行此操作吗?

1 个答案:

答案 0 :(得分:2)

MySQL不会强制执行约束,因此无论这些是否有效都无关紧要。

您需要使用触发器来强制执行此类条件。如果您允许更新,则需要更新并插入触发器。

insert触发器看起来像这样:

CREATE TRIGGER t_trigger_insert ON t BEFORE INSERT
FOR EACH ROW
BEGIN
    IF (EXISTS (SELECT 1
                FROM t t2
                WHERE t2.EQUIPMENT_ID = NEW.EQUIPMENT_ID AND
                      t2.INSPECTION_ID = NEW.INSPECTION_ID AND
                      t2.INSPECTION_DATE > NEW.INSPECTION_DATE
               )
       ) THEN
        SIGNAL SQLSTATE '45000'
            SET MESSAGE_TEXT = 'A later date already exists';
    END IF;
END;