问题
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