not null 非空约束:所在列的值不能为null
create table t1(id number,name varchar2(20) not null);
唯一约束:unique 所在列的值不能重复,但是可以为null
create table t2(id number unique,name varchar2(20) not null);
主键约束:所在列不能重复也不能为null,每个表有且只有一个主键;
create table t3(id number primary key,name varchar2(20) not null);
外键约束
create table class(c_id number primary key,c_name varchar2(20) not null unique);
create table stu(s_id number primary key,
s_name varchar2(20) not null,
classId number references class(c_id)
);
检查约束(条件):check
create table t4(
id number,
name varchar2(20),
sex char(4) check(sex in ('男','女')),
score number check(score >=60 and score<=100)
);
示例
创建goods表
SQL> create table goods(
2 goodsId number primary key,
3 goodsName varchar2(64) not null,
4 price number check(price>0),
5 category varchar2(200),
6 provider varchar2(200)
7 );
Table created
创建customer表
SQL> create table customer(
2 customerId number primary key,
3 name varchar2(20) not null,
4 address varchar2(200),
5 email varchar2(64) unique,
6 sex char(2) default '男' check(sex in ('男','女')),
7 cardId varchar2(18) unique
8 );
Table created
创建purchase表
SQL> create table purchase(
2 c_Id number references customer(customerId),
3 g_Id number references goods(goodsId),
4 nums number check(nums>=1 and nums<=30),
5 primary key(c_Id,g_Id)
6 );
Table created
修改约束
a. 修改非空约束 not null
alter table goods modify price not null;
b.修改或添加 unique(唯一)、 primary key(主键)、 foreign key(外键)和check(检查)约束
语法:alter table 表名 add constraint 约束名 约束种类(字段);
添加主键
create table t5(id number, name varchar2(20));
alter table t5 add constraint PK_id primary key(id);
添加唯一约束
例子:给商品名称添加 唯一约束
alter table goods add constraint Uk_gName unique(goodsName);
添加 检查约束
例子:增加客户的住址只能是(伊滨区, 老城区, 洛龙区)
alter table customer add constraint CK_address check(address in ('伊滨区','老城区','洛龙区'));
删除约束
语法:alter table 表名 drop constratint 约束名称;
在删除主键约束的时候,可能有错误,比如: alter table 表名 drop primary key;这是因为如果在两张表存在主从关系,那么在删除主要的主键约束时,必需带上 cascade 选项。
基本语法:alter table 表名 drop primary key cascade;
例子:删除班级表的主键
alter table class drop primary key cascade;