如何设置mysql日期的最小值和最大值?

How to set mysql date minimum and maximum value?

是否可以在 MySQL table 定义中设置最小值和最大值?

例如:

CREATE TABLE `tbl` (
    `id` BIGINT UNSIGNED NOT NULL PRIMARY KEY,
    `born` DATE MIN('1900-01-01') MAX('1999-12-31')
);

如果我对你的理解正确,你可以使用触发器来强制执行日期范围:

CREATE TABLE `tbl` (
    `id` BIGINT UNSIGNED NOT NULL PRIMARY KEY,
    `born` DATE
);                 

CREATE TRIGGER `tbl_trg_ins` BEFORE INSERT ON  `tbl`
FOR EACH ROW
BEGIN
    IF (NEW.`born` < '1900-01-01' OR NEW.`born` > '1999-12-31') THEN
    SIGNAL SQLSTATE '10000'
        SET MESSAGE_TEXT = 'check constraint on tbb failed during insert';
    END IF;
END;

CREATE TRIGGER `tbl_trg_upd` BEFORE UPDATE ON  `tbl`
FOR EACH ROW
BEGIN
    IF (NEW.`born` < '1900-01-01' OR NEW.`born` > '1999-12-31') THEN
    SIGNAL SQLSTATE '10000'
        SET MESSAGE_TEXT = 'check constraint on tbl failed during update';
    END IF;
END;

INSERT INTO `tbl`
VALUES (1, '1990-12-12');

-- INSERT INTO `tbl`
-- VALUES (2, '2001-12-12');
-- 'check constraint on tbb failed during insert'

SqlFiddleDemo

当用户尝试 update/insert 不在 1900-01-011999-12-31 之间的值时,他会得到错误。