MySQL 中的 CHECK 约束不起作用

2021-11-20 00:00:00 mysql check-constraints

首先我创建了一个表格

CREATE TABLE Customer (
  SD integer CHECK (SD > 0),
  Last_Name varchar (30),
  First_Name varchar(30)
);

然后在该表中插入值

INSERT INTO Customer values ('-2','abc','zz');

MySQL 没有显示错误,它接受了值.

MySQL doesn't show an error, it accepted the values.

推荐答案

MySQL 8.0.16 是第一个支持 CHECK 约束的版本.

MySQL 8.0.16 is the first version that supports CHECK constraints.

阅读https://dev.mysql.com/doc/refman/8.0/en/create-table-check-constraints.html

如果您使用 MySQL 8.0.15 或更早版本,MySQL参考手册说:

If you use MySQL 8.0.15 or earlier, the MySQL Reference Manual says:

CHECK 子句被解析但被所有存储引擎忽略.

The CHECK clause is parsed but ignored by all storage engines.

尝试触发器...

mysql> delimiter //
mysql> CREATE TRIGGER trig_sd_check BEFORE INSERT ON Customer 
    -> FOR EACH ROW 
    -> BEGIN 
    -> IF NEW.SD<0 THEN 
    -> SET NEW.SD=0; 
    -> END IF; 
    -> END
    -> //
mysql> delimiter ;

希望有所帮助.

相关文章