多条件检查约束MySQL

vxf3dgd4  于 2022-09-18  发布在  Java
关注(0)|答案(1)|浏览(170)
CREATE TABLE shoesize( 
nr TINYINT NOT NULL,
shoesize VARCHAR(6) NOT NULL,

CHECK (shoesize = 'mini' OR 'medium' OR 'maxi'),
PRIMARY KEY (nr)
)engine=innodb;

insert into shoesize(nr,shoesize) values ('1','mini');
insert into shoesize(nr,shoesize) values ('2','medium');
insert into shoesize(nr,shoesize) values ('3','maxi');
insert into shoesize(nr,shoesize) values ('4','ultra');
insert into shoesize(nr,shoesize) values ('5','mega');

    Error Code: 3819. Check constraint 'shoesize_chk_1' is violated.    0.015 sec

我试着做一个限制,那就是只接受特定文本的鞋子。但是,当我尝试输入数据时,会触发该约束。在我看来,支票上应该有OR吧?

dy1byipe

dy1byipe1#

您的问题是只检查了第一个值mini,但您需要重复这个等式才能得到其余的值

CREATE TABLE shoesize( 
nr TINYINT NOT NULL,
shoesize VARCHAR(6) NOT NULL,

CHECK (shoesize = 'mini' OR  shoesize =  'medium' OR shoesize = 'maxi'),
PRIMARY KEY (nr)
)engine=innodb;

insert into shoesize(nr,shoesize) values ('1','mini');
insert into shoesize(nr,shoesize) values ('2','medium');
insert into shoesize(nr,shoesize) values ('3','maxi');
insert into shoesize(nr,shoesize) values ('4','ultra');
insert into shoesize(nr,shoesize) values ('5','mega');
SELECT * FROM shoesize

Nr|鞋码

1|迷你
2|中等
3|maxi

fiddle

相关问题