mysql 检查约束 替代_检查约束不适用于mysql

CREATE TABLE IF NOT EXISTS supervisor (

sup_id INT(3) NOT NULL,

sup_name VARCHAR(30) NOT NULL,

gen VARCHAR(1) NOT NULL CHECK (gen='M' or gen='F'),

dep_id INT(4),

PRIMARY KEY (sup_id),

INDEX (dep_id),

FOREIGN KEY (dep_id)

REFERENCES department(dep_id)

ON UPDATE CASCADE ON DELETE RESTRICT

);

我也尝试过:

CONSTRAINT chk_supervisor_gen CHECK ('M' or 'F')

这些都没有阻止输入此信息

INSERT

INTO supervisor (sup_id, sup_name, gen, dep_id)

VALUES

(1, 'hello', 'G', 1);

解决方法:

MySQL不强制执行检查约束.

这是与SQL标准的有据可查的偏差. (尽管这是始料未及的.)

如果您需要MySQL数据库来实施“检查约束”,则必须将实施编码为BEFORE INSERT和BEFORE UPDATE触发器.

注意事项:

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

在CREATE TABLE语法下嵌入在MySQL参考手册中.

关于枚举的警告

ENUM不会限制插入“无效”值.无效的值将转换为零长度的字符串,会发出警告,但这不是错误.

示范:

CREATE TABLE foo (gen ENUM('M','F'))

INSERT INTO foo (gen) VALUES ('x')

-- Warning Code : 1265

-- Data truncated for column 'gen' at row 1

SELECT gen, CHAR_LENGTH(gen) FROM foo;

-- gen CHAR_LENGTH(gen)

-- --- ----------------

-- 0

标签:check-constraints,sql,mysql

来源: https://codeday.me/bug/20191012/1900491.html

你可能感兴趣的:(mysql,检查约束,替代)