check constraint won't work mysql [duplicate]

南楼画角 提交于 2020-01-11 11:08:32

问题


check constraint won't work

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    
);

i also tried:

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

neither of these stopped this information being entered

INSERT
INTO supervisor (sup_id, sup_name, gen, dep_id)
VALUES  
       (1, 'hello', 'G', 1);

回答1:


MySQL doesn't enforce check constraints.

This is a well documented deviation from the SQL standard. (Though it unexpected by the uninitiated.)

If you need the MySQL database to enforce a "check constraint", the enforcement has to be coded into a BEFORE INSERT and a BEFORE UPDATE trigger.


This note:

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

is buried in the MySQL Reference Manual, under the CREATE TABLE syntax.

Reference: https://dev.mysql.com/doc/refman/5.5/en/create-table.html


WARNING ABOUT ENUM

An ENUM does not restrict "invalid" values from being inserted; an invalid value is translated into a zero length string, a warning is issued, but it's not an error.

Demonstration:

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



回答2:


Unfortunately MySQL does not support SQL check constraints. So try using enum instead

CREATE TABLE IF NOT EXISTS supervisor (
sup_id INT(3) NOT NULL,
sup_name VARCHAR(30) NOT NULL,
gen enum('M','F') NOT NULL,
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    
);


来源:https://stackoverflow.com/questions/30635847/check-constraint-wont-work-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!