MySQL —约束

约束是创建表/修改表的时候,对字段的约束

primary key 主键约束,主键是一行数据的唯一标识,要求非空且唯一

auto_increment 自动增长

not null 非空约束 限制该字段的数据不能为null

unique 唯一约束 保证该字段的所有数据都是唯一,不重复的

default 默认约束 保存数据时,如果未指定该字段的值,则采用默认值

check 检查约束(8.0.16版本之后) 保证字段满足某一个条件

使用方法如下 

create table user (
    id int primary key auto_increment comment 'id主键',
    name varchar(10) not null unique comment '姓名',
    age  int check ( age>0 and age<120 )  comment '年龄',
    status char(1) default '1' comment '状态',
    gender char(1) comment '性别'
)comment '用户表';

外键约束

具有外键的表为子表,外键所关联的表为父表

 foreign key 外键约束 用来让两张表的数据之间建立链接,保证数据的一致性和完整性

添加外键:

创建表时添加

create table 表名(

        字段名 数据类型,

        ......

        [constraint] [外键名称] foreign key(外键字段名) references 主表(主表列名)

);

给已存在表新增外键

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

alter table emp add constraint fk_emp_dept_id foreign key (dept_id) references dept(id);

 删除外键

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

alter table emp drop foreign key fk_emp_dept_id;

外键的删除/更新行为

no action/restrict : 当父表重删除/更新对应记录时,首先检查该记录是否有对应外键,如有则不允许删除/更新。

cascade :当在父表中删除/更新对应记录时,有对应外键,则也删除/更新外键在子表中的记录。

set null :当在父表中删除/更新对应记录时,有对应外键,则设置子表中该外键值为null(需该外键允许取null)

set default :父表变更时,子表将外键列设置成一个默认的值(Innodb不支持)

设置更新时为cascade,删除时为no action

alter table emp 
add constraint fk_emp_dept_id foreign key (dept_id) references dept(id) 
on update cascade on delete no action;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值