Add constraint on values , Mysql

2019-03-01 13:14发布

问题:

My table

CREATE TABLE STUDENT ( 
      BCN INT not null,
      Stname varchar(50) not null,
      Sex char(1) not null ,
      primary key (BCN));

I want to make Sex attribute just accept two values 'F' or 'M'

I've try 'check' clause :

 Sex char(1) not null check (Sex = 'F' or Sex ='M' ) 

but doesn't work, the Sex column still accept other values like ('B') !

and I've try to create trigger :

DELIMITER $$ CREATE TRIGGER SexCheck BEFORE INSERT ON student
FOR EACH ROW
BEGIN
    IF Sex <> 'M' and Sex <> 'F' THEN
    SIGNAL SQLSTATE '10000'
        SET MESSAGE_TEXT = 'check constraint on Student.Sex failed';
    END IF;
END$$   
DELIMITER ;

It doesn't produce any syntax error , but the Sex column doesn't accept any values even 'M' or 'F'! it shows the message that I've set .

how can I fix that?

-I'm using mysql workbench 6.3.

Thanks in advance

回答1:

From CREATE TABLE:

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

Second:

CREATE TRIGGER SexCheck BEFORE INSERT ON  STUDENT
FOR EACH ROW
BEGIN
    IF New.Sex NOT IN('F', 'M') THEN
    SIGNAL SQLSTATE '10000'
        SET MESSAGE_TEXT = 'check constraint on Student.Sex failed';
    END IF;
END;


INSERT INTO STUDENT(Sex) VALUES ('B');
-- check constraint on Student.Sex failed

SqlFiddleDemo



回答2:

Use the MySQL ENUM type. "An ENUM is a string object with a value chosen from a list of permitted values that are enumerated explicitly in the column specification at table creation time."

sex ENUM ('M', 'F')