MySQL基础-约束
注意:约束时作用于表中的字段上的,可以在创建表或者修改表的时候添加约束
约束
- auto_increment 自动增长
- not null 非空约束
- unique 唯一约束
create table user(
id int primary key auto_increment comment '主键',
name varchar(10) not null unique comment '姓名
/*
因为MySql不是8.0.16之后的版本,无法使用检查约束
*/
age int comment '年龄',
status char(1) default '1' comment '状态',
gender char(1) comment '性别'
)comment '用户表';
-- 主键约束 primary key(自增 AUTO_INCREMENT)
insert into user(name, age, status, gender) values ('Tom1','19','1','男'),('Tom2','25','0','男');
-- 非空约束 not null
insert into user(name, age, status, gender) values (null,'19','1','男');
-- 唯一约束 unique
insert into user(name, age, status, gender) values ('Tom1','19','1','男');
-- 检查约束 check() MySql 8.0.16之后可用
外键约束
注意:数据库中的两张表,如未在数据库层面建立外键链接,是无法保证数据的一致性和完整性的。
-- 添加外键
alter table employees add constraint fk_employees_dept_id foreign key (dept_id) references dept(id);
-- 删除外键
alter table employees drop foreign key fk_employees_dept_id;
删除/更新行为
-- 删除或者更新时绑定更新操作
alter table employees add constraint fk_employees_dept_id foreign key (dept_id) references dept(id) on update cascade on delete cascade ;
-- 删除或者更新时绑定设null操作
alter table employees add constraint fk_employees_dept_id foreign key (dept_id) references dept(id) on UPDATE set null on DELETE set null ;