因为MySQL不支持传统的CHECK约束,因此通过ENUM和SET类型可以解决一部分问题。
下面通过一个小demo来演示一下
ENUM
drop table if EXISTS test;create table test(user varchar(30),sex enum('male','female'))ENGINE=INNODB;insert into test select 'haha1','male';insert into test select 'haha2','female';insert into test select 'haha3','nofemal';
执行上面的语句,执行到最后一行sql语句的时候报错
因为“haha3”中的sex值不是male和female的其中之一。
SET
drop table if EXISTS test2;create table test2(user varchar(30),sex SET('male','female'))ENGINE=INNODB;insert into test2 select 'haha1','male';insert into test2 select 'haha2','female';insert into test2 select 'haha3','nofemal';
执行上面的sql语句也是到最后一行报错
原因也是因为’nofemal’不是他们其中的’male’和’female’不是其中的任何一个。
注意:
ENUM和SET类型都是集合类型,不同的是ENUM类型最多可枚举65535个元素,而SET类型最多枚举64个元素。且set中可以存set枚举中的组合,比如执行
insert into test2 select ‘haha4’,’ 'male', 'female'’;
也可以成功。