完整性
- 定义
- 分类:实体完整性、域完整性、用户定义完整性
- 创建约束(主键、外键)
(1) 创建表的同时创建约束
1) 主键primary key
2) 外键foreign key
父关键字在自己表中必须是主键;
父子必须完全一样
3) 唯一unique
4) 默认值default
举例
create table student
(sno char(4) primary key,
sname char(20) not null,
sageint,
ssex char(2) default ‘男’);
create table sc
(sno char(4),
cno char(3),
gradeint,
constraintpk_sc primary key(sno,cno),
constraint fk1_sc foreign key(sno) references student(sno));
(2) 表已经存在,添加约束
1) 主键
alter table student
add primary key(sno);
alter table sc
add primary key(sno,cno);
2) 外键
alter table sc
add constraint fk1_sc foreign key(sno) references student(sno);
3) 唯一
alter table student
add constraint uni unique(sname);
4. 查看约束
show create table student;
5. 删除约束
1)主键
alter table student
drop primary key;
2)外键
alter table sc
drop foreign key fk1_sc;
3)唯一
alter table student
drop index uni;