MySQL基础教程14——约束

117 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第30天,点击查看活动详情

MySQL基础教程14——约束

非空约束(not null)

例子:

telephone char(10) not null;

删除:

alter table xxx modify 字段名 要保留的约束;

非空约束限制的字段在添加数据时如果字段值为null会向数据库申请一次主键(会影响自增字段的值)。

唯一约束(unique)

例子:

name varchar(10) unique;

删除:

alter table xxx drop index 字段名;

唯一约束的字段值不能为重复值,若为已有值则会报错。

主键约束(primary key)

自增字段:auto_increment

例子:

id int primary key auto_increment;

删除:

alter table xxx drop primary key;

若主键被空值申请但数据为被添加则自增一次。

默认约束(default)

例子:

status char(1) default '默认值';

删除:

alter table xxx modify 字段名 要保留的约束;

设置过默认约束的字段在添加数据时若无添加则自动将值改为默认值。

检查约束(check)

例子:

age int check(age>0 and age<=120);

删除:

alter table xxx modify 字段名 要保留的约束;

若添加值在检查约束条件外无法添加。

外键约束

create table 表名)
    字段名 字段类型,
    ....
    constraint 外键名称 foreign ky 外键字段名 references 主表(主表列名)
    );

外键名称:自行定义的名称 外键字段名:子表需要连接的键 主表(主表列名):父表(主键)

修改已经创建的表的外键

alter table 表名 add constraint 外键名称 foreign key (外键字段名) references 主表(主表列名);

删除已经创建的表的外键

alter table 表名 drop foreign key 外键名称;

外键的删除与更新

cascade(子表随着父表更新/删除 而 更新/删除)

alter table 表名 add constaint 外键名称 foreign key (外键字段名) references 主表(主表列名) on update cascade on delete cascade;

set null(父表删除时子表若有数据则改为null)

alter table 表名 add constaint 外键名称 foreign key (外键字段名) references 主表(主表列名) on update set null on delete set null;

(点击进入专栏查看详细教程)