约束 描述 关键字
非空约束 限制该字段的数据不能为null not null
唯一约束 保证该字段的所有数据都是唯一,不重复的 unique
主键约束 主键是一行数据的唯一标识,要求非空且唯一 primary key
默认约束 保存数据时,如果未指定该字段的值,则采用默认值 default
检查约束(8.0.16版本之后) 保证字段值满足一个条件 check
外键约束 用来让两张表的数据之间建立连接,保证数据的一致性和完整性 foreign key
注意:约束是作用于表中字段上的,可以在创建表/修改表的时候添加约束
约束条件 约束关键字
主键,并且自动增长 primary key , auto_increment
不为空,并且唯一 not null , unique
大于0,并且小于等于120 check
如果没有指定该值,默认为1 default
外键约束 :
添加外键的语法
create table 表名(
字段名 数据类型,
...
[constraint] [外键名称] foreign key (外键字段名)
references 主表(主表列名)
);
alter table 表名 add constraint 外键名称 foreign key (外键字段名) references 主表(主表列名);
删除外键的语法
alter table 表名 drop foreign key 外键名称;
删除/更新行为
行为 说明no action 当在父表中删除/更新对应记录时,首先检查该 记录是否有对应的外键,如果有则不允许删除/ 更新
restrict(和no action效果相同) 当在父表中删除/更新对应记录时,首先检查该 记录是否有对应的外键,如果有则不允许删除 /更新
cascade 当在父表中删除/更新对应记录时,首先检查 该记录是否有对应的外键,如果有,则也删除 /更新外键在字表中的记录
set null 当在父表中删除/更新对应记录时,首先检查 该记录是否有对应的外键,如果有则设置子表 中该外键值为null(这就要求该外键允许取null)
alter table 表名 add constraint 外键名称
foreign key (外键字段) references 主表名(主表字段名)
on update cascade on delete cascade
约束演示
primary key,auto_increment 主键,并且自动增长
not null , unique 不为空,并且唯一
check 大于0 ,并且小于等于120
default 如果没有指定默认值,默认为1
-- 约束演示
create table user(
id int primary key auto_increment comment '主键',
name varchar(10) not null unique comment '姓名',
age int check ( age>0 && age <= 120 ) comment '年龄',
status char(1) default '1' comment '身份',
gender char(1) comment '性别'
) comment '用户表';
-- 插入数据
insert into user( name, age, status, gender) values
('张三',19,'1','男'),('李四',20,'0','女');
外键约束代码演示
-- 约束(外键)
-- 父表
create table dept(
id int auto_increment comment 'ID' primary key ,
name varchar(50) not null comment '部门名称'
)comment '部门表';
insert into dept (id, name) VALUES (1,'研发部'),(2,'市场部'),(3,'财务部'),(4,'销售部'),(5,'总经部');
-- 字表
create table emp(
id int auto_increment comment 'Id' primary key ,
name varchar(50) not null comment '姓名',
age int comment '年龄',
job varchar(20) comment '职位',
salary int comment '薪资',
entrydate date comment '入职时间',
managerid int comment '直属领导ID',
dept_id int comment '部门ID'
)comment '员工表';
insert into emp(id, name, age, job, salary, entrydate, managerid, dept_id) VALUES
(1,'张三',66,'总裁',20000,'2000_01_01',null,5),(2,'李四',20,'项目经理',12500,'2005-12-05',1,1),
(3,'王五',33,'开发',8400,'2000-11-03',2,1),(4,'老刘',48,'开发',11000,'2002-02-05',2,1),
(5,'小邱',20,'开发',10500,'2004-09-07',3,1),(6,'小秦',19,'程序员鼓励师',6600,'2004-10-12',2,1);
-- 添加外键
alter table emp add constraint fk_emp_dept_id foreign key (dept_id) references dept(id);
-- 删除外键
alter table emp drop foreign key fk_emp_dept_id;
外键的删除和更新行为
-- 外键的删除和更新行为
alter table emp add constraint fk_emp_dapt_id foreign key (dept_id) references dept(id)
on update set null on delete set null ;
alter table emp add constraint fk_emp_dapt_id foreign key (dept_id) references dept(id)
on update cascade on delete cascade ;
总结
约束是作用于表中字段上的,可以在创建表、修改表的时候添加约束
外键的作用是保证数据的一致性和完整性