概念
- 创建表是添加约束条件
- 通过修改来添加约束条件
分类
primary key (主键)
非空且唯一
- 创建表时添加
//方式一:
create table(userid number,
constraint pk_user primary key(userid),
username varchar2(10));
//方式二:
create table(userid number primary key,
username varchar2(10));
- 创建表后添加主键
alter table tablename add constraint pk_user primary key(userid);
- 删除主键约束
alter table student drop constraint pk_user;
alter table student drop primary key;
foreign key (外键)
一个表中非主键字段的值是另外一个表中主键的值
- 创建表时添加
//方式一
create table student(username number constraint fk_user references user(userid));
//方式二
create table student(username number, constraint fk_user foreign key(username) references user(userid));
- 添加约束条件
alter table tablename add constraint fk_user foreign key(usercon) references dept(dept_id(主键));
- 删除约束条件
alter table tablename drop constraint fk_user;
not null(非空)
- 创建字段时添加
alter table student add stu_sex number not null;
- 给已有字段添加
alter table student modify student_id not null;
unique(唯一)
- 创建时添加约束
alter table student add stu_no number unique;
- 给已有字段添加约束
alter table student modify stu_no unique;
注意点:以上都可以在创建表的时候就设置好
check(强制满足条件)
假定在sal列上定义了check约束,并要求sal列值在1000~2000之间,如果不在1000~2000之间就会提示出错。
- 添加字段时添加约束条件
alter table staff add staff_sal number check(staff_sal between a and b);
- 给已有字段添加约束
alter table staff modify staff_sal check(staff_sal between 1000 and 4000);