1 Fork me on GitHub

30. SQL--check:检查性约束

1. 前言

sql check 约束(检查性约束)用来限制字段的取值范围。您可以在 check 约束中添加限制条件,只有满足这些条件的值才允许进入该字段。

您可以为一个字段或者多个字段定义 check 约束。

2. 示例

创建一个名为 website 的新表,该表包含七个字段,我们为 age 字段添加 check 约束,要求网站年龄不大于 25 岁。代码如下:

create table website (
    id      int              not null   auto_increment,
    name    varchar(20)      not null,
    url     varchar(30),
    age     tinyint unsigned not null check(age<=25),
    alexa   int unsigned     not null,
    uv      float                       default '0',
    country char(3)          not null ,
    primary key (id)
);

它一些常见用法:

`1. 规定体重必须大于 0 并且小于 100 公斤:

weight NUMERIC(9, 2) CHECK( weight>0 AND weight<=100 )

2. 规定性别只能是男(male)和女(female):

sex char(6) check( sex='male' or sex='female' )

当然,您也可以为多个字段添加 CHECK 约束。例如,在创建 website 表时,规定网站年龄不大于 25 岁,并且 Alexa 排名不能高于 10000,如下所示:

create table website (
    id      int              not null   auto_increment,
    name    varchar(20)      not null,
    url     varchar(30),
    age     tinyint unsigned not null check(age<=25),
    alexa   int unsigned     not null check(alexa<=10000),
    uv      float                       default '0',
    country char(3)          not null ,
    primary key (id)
);

或者写作:

create table website (
    id      int              not null   auto_increment,
    name    varchar(20)      not null,
    url     varchar(30),
    age     tinyint unsigned not null,
    alexa   int unsigned     not null,
    uv      float                       default '0',
    country char(3)          not null ,
    primary key (id),
    constraint mycheck check(age<=25 and alexa<=10000)
);

myCheck 为自定义的约束名字。

如果您已经创建了 website 表,并且希望向 age 字段添加约束,则可以使用下面的语句:

alter table website
modify age tinyint unsigned not null check(age<=25);

如果您希望给多个字段添加约束,可以使用下面的语法:

alter table website
add constraint mycheck check(age<=25 and alexa<=10000);

3. 删除约束

要想删除 check 约束,请使用下面的语法:

alter table website
drop constraint mycheck;

 

posted @ 2022-08-31 18:03  v_jjling  阅读(424)  评论(0编辑  收藏  举报
AmazingCounters.com