Oracle如何给数据库添加约束过程解析
主键约束(两个特性)
1:主键必须写
2:主键不可重复
create table stu01( sid varchar(100), sname varchar2(100) --constraint PK_stu01_sid primary key (sid) ) --添加约束(主键) alter table stu01 add constraint PK_stu01_sid primary key(sid) ---添加主键约束 alter table stu01 drop constraint PK_stu01_sid ---删除主键约束
唯一约束(UNIQUE)
唯一,但是可以为空
create table stu02( sid varchar2(100), sname varchar2(100), constraint PK_stu02_sid primary key(sid), constraint UK_stu02_sname unique(sname) )
非空约束(not null)
一般简写
create table stu03( sid varchar2(100), sname varchar2(100) not null, constraint PK_stu03_sid primary key(sid), constraint UK_stu03_sname unique(sname) )
外键约束
先添加学生表、和课程表
create table stu04( sid varchar2(100), sname varchar2(100) not null, constraint PK_stu04_sid primary key(sid), constraint UK_stu04_sname unique(sname) ) --创建课程表 create table course01( cid varchar2(100), cname varchar2(100) not null, constraint PK_course01_cid primary key(cid), constraint UK_course01_cname unique(cname) ) --最后添加成绩表,外键约束课程表和学生表 create table mark02( sid varchar2(100), cid varchar2(100), mark number, constraint PK_mark02_sidAndcid primary key(sid,cid), constraint FK_mark02_sid foreign key(sid) references stu04(sid), constraint FK_mark02_cid foreign key(cid) references course01(cid), constraint UK_mark02_mark unique(mark) ) --删除外键约束 alter table mark01 drop constraint FK_mark02_sid alter table mark01 drop constraint FK_mark02_cid