一.概念
- 约束:作用于表中字段上的规则,用于限制存储在表中的数据
- 目的:保证数据库中数据的正确,有效性和完整性。
- 分类:非空约束(not null),唯一约束(unique),主键约束(primary key),默认约束(default),检查约束(check),外键约束(foreign key)。
二.运用
创建约束表:(也可以直接在创建新表目录,选择创建约束,不需要写代码)
create table user(
id int primary key auto_increment comment '主键',
name varchar(10) not null unique comment '姓名',
age int check ( age > 0 && age <= 100 ) comment '年龄',
status char(1) default '1' comment '状态',
gender char(1) comment '性别'
) comment '用户表';
约束条件:
插入数据:(插入的数据一定要在约束条件内,否则报错)
insert into user(name,age,status,gender) values ('是1',99,'1','男'),('是二',22,'1','女');
三.外键约束
概念:用来让两张表的数据之间建立连接,保证数据的一致性和完整性
语法:
create table 表名(
字段名 数据类型,
....
[constraint] [外键名称] foreign key(外键字段名) references 主表(主表列名)
);
准备副表数据:
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 emp2(
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 emp2 (id, name, age, job,salary, entrydate, managerid, dept_id) VALUES
(1, '谢谢', 26, '董事长',30000, '2004-02-08', null,5),
(2, '孙悟空', 56, '项目经理',20000, '2007-07-08', 1,1),
(3, '猪八戒', 43, '开发',15000, '2012-05-12', 2,1),
(4, '沙和尚', 38, '开发',17000, '2014-03-08', 2,1),
(5, '唐僧', 57, '总经理',25000, '2016-02-12', 3,1),
(6, '飞天', 67, '财务',11000, '2018-02-08', 2,1);
添加外键(注意表名的不同)
--添加外键
alter table emp2 add constraint fk_emp_dept_id foreign key (dept_id) references dept(id);
删除外键
--删除外键
alter table emp2 drop foreign key fk_emp_dept_id ;
外键的删除和更新行为:
- no action---当父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有不允许删除/更新
- restrict---当父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有不允许删除/更新
- cascade----当父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有,则也删除/更新外键在子表中的记录
- set nll----当父表中删除对应记录时,首先检查该记录是否有对应外键,如果有则设置子表中该外键值为null
- set default---父表有变更时,子表将外键列设置成一个默认的值
演示cascade行为(也可以在表中点击modify table,shan删除/添加外键操作)
--外键的删除和更新
alter table emp2 add constraint fk_emp_dept_id foreign key (dept_id) references dept(id) on update cascade on delete cascade ;