关于oracle数据库维护数据的完整性--约束

首先是五个约束关键字:

1.primary key(主键约束):唯一标识数据库表中的每条记录,每个表中有且只有一个主键,且不能为null,它可以包含表中的一个或多个字段(复合主键)

2.unique(唯一约束):唯一标识数据库表中的每条记录,每个表中可以有多个unique,可以为null

3.foreign key(外键约束):一个表中的 foreign key 指向另一个表中的 primary key

4.check(条件约束):约束用于限制列中的值的范围

5.not null(非空约束):约束强制列不接受 null 值

下面用一个小的案例来演示他们的用法:

商品goods(商品号goodsId,商品名 goodsName,单价 unitprice,商品类别category,供应商provider);
客户customer(客户号customerId,姓名name,住在address,电邮email,性别sex,身份证cardId);
购买purchase(客户号customerId,商品号goodsId,购买数量nums);

必须包含下面的约束:

(1). 每个表的主外键;
(2). 客户的姓名不能为空值;
(3). 单价必须大于0,购买数量必须在1到30之间;
(4). 电邮不能够重复;
(5). 客户的性别必须是 男 或者 女,默认是男;

<pre name="code" class="sql"><strong>/*商品goods(商品号goodsId,商品名 goodsName,单价 unitprice,商品类别category,供应商provider); */
create table goods(
goodsId char(8) primary key,--主键约束
goodsName varchar2(40) ,
unitPrice number(10,2) check(unitPrice>0),--check约束
categories varchar2(40),
provider varchar2(40)
);
/*客户customer(客户号customerId,姓名name,住在address,电邮email,性别sex,身份证cardId);*/
create table customers(
customerId char(8)primary key,--主键约束
customerName varchar2(20) not null,--不为空约束
address varchar2(80),
email varchar2(40) unique,--unique约束
sex char(4) default '男' check(sex in ('男','女')) ,--check约束
cardId char(18)
);</strong>
/*购买purchase(客户号customerId,商品号goodsId,购买数量nums);*/
create table purchase(
customerId references customers(customerId),--外键约束
goodsId references goods(goodsId),--外键约束
nums number check(nums between 1 and 30)--check约束
);

 此时出现了新的需求:(修改约束) 

(1) 增加商品名也不能为空

<strong>alter table goods modify goodsName not null;--如果要删除not null约束 只需要把not null改为null
alter table goods modify goodsName null;</strong>

(2) 增加身份证也不能重复

<strong>alter table customer add constraint add_unique unique(cardId);--add_unique 只是为这个添加约束设置的一个名字
/*如果要删除这个约束*/
alter table customer drop constraint add_unique;</strong>

(3) 增加客户的住址只能是’海淀’,’朝阳’

<strong>alter table customers add constraint add_check check(address in('海淀','朝阳'));
</strong>
当你想要删除带有主外键约束的表时:

1.在drop table [表名] 后面加上cascade constraint

drop table customers cascade constraint;
2.先删除表的主外键约束,再进行表的删除

alter table customers drop primary key cascade;
3.先删除子表再删除主表


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值