一、约束
1、概念:约束是作用于表中字段上的规则,用于限制存储在表中的数据
2、目的:保证数据库中数据的正确性,有效性和完整性
3、分类:
注意:约束是作用于表中字段上的,可以在创建表、修改表的时候添加约束
二、根据需求完成表的创建
create table user(
id int primary key auto_increment comment 'ID',
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 '用户表';
1、主键自动增长的实现
并没有插入id的值,但是id可以进行自动增长
insert into user(name, age, status, gender)
values('xhm1',18,'1','女'),('xhm2',18,'1','女');
2、name不为空且唯一
3、年龄需要大于0小于等于120
4、默认值
insert into user(name, age, gender)
values('xhm4',24,'女');
三、外键约束
1、概念:外键是用来让两张表的数据之间建立连接,从而保证数据的一致性和完整性
创建两张表为实例:
create table employ(
id int primary key auto_increment comment 'ID',
name varchar(10) not null comment '姓名',
age int comment '年龄',
job varchar(10) comment '职位',
salary int comment '薪资',
entrydate date comment '入职时间',
managerid int comment '直属领导ID',
dept_id int comment '部门ID'
)comment '员工表';
insert into employ(name,age, job, salary, entrydate, managerid, dept_id)
VALUES ('金庸',66,'总裁',20000,'2000-01-01',null,5),
('张无忌',20,'项目经理',12500,'2005-12-01',1,1),
('杨晓',33,'开发',8400,'2000-11-12',2,1),
('韦一笑',48,'开发',11000,'2002-05-01',2,1),
('常遇春',43,'开发',10500,'2004-09-07',3,1),
('小赵',19,'人事',5000,'2023-08-08',2,1);
create table dept(
id int auto_increment comment 'ID' primary key ,
name varchar(20) not null comment '部门名称'
)comment '部门分类';
insert into dept(name) values ('研发部'),('市场部'),('财务部'),('销售部'),('总经办');
2、语法:添加外键
create table 表名(
字段名 数据类型,
...
[constraint] [外键名称] foreign key(外键字段名) references 主表(主表列名)
);
alter table 表名 add constraint 外键名称 foreign key (外键字段名) references 主表(主表列名);
为上面的两张表添加外键
alter table employ add constraint fk_employ_dept_id foreign key (dept_id) references dept(id);
删除外键:
alter table 表名 drop foreign key 外键名称;
alter table employ drop foreign key fk_employ_dept_id;
4、删除/更新行为
alter table 表名 add constraint 外键名称 foreign key(外键字段) references 主表名(主表字段名)
on update cascade on delete cascade;
alter table employ add constraint fk_emp_dept_id foreign key (dept_id) references dept(id) on update cascade on delete cascade;
alter table employ add constraint fk_emp_dept_id foreign key (dept_id) references dept(id) on update set null on delete set null ;