7.windows-oracle实战第七课 --约束、索引

数据的完整性

     数据的完整性用于确保数据库数据遵从一定的商业和逻辑规则。数据的完整性使用约束、触发器、函数的方法来实现。在这三个方法中,约束易于维护,具备最好的性能,所以作为首选。

 约束:not null、unique(可以为空,不能重复) 、primary key、foreign key、check

一个表中只能有一个主键,但是可以有多个unique.

 

案例:

现有一个商店数据库,有三个表:

商品表goods(商品号goodsId,商品名goodsName,单价unitprice,商品类别category,供应商provider);

客户表customer(客户号customerId,姓名name,地址address,电邮email,性别sex,身份证cardId);

购买purchase(客户号customerId,商品号goodsId,购买数量nums);

1.建表,定义要求如下:

 (1)每个表有主外键;

 (2)客户的姓名不能为空值;

 (3)单价必须大于0,购买数据必须在1到30之间;

 (4)电邮不能重复

 (5)客户性别是男女,默认为男

goods:

create table goods(goodsId  char(8) primary key,--主键,主键名字是系统分配的
goodsName varchar2(30),
unitprice number(10,2) check(unitprice>0),
category varchar2(8),
provider varchar2(30));

customer:

create table customer(customerId number(8) primary key,--主键
name varchar2(50) not null,
address varchar2(50),
email varchar2(50)  unique,
sex  char(2) default '男' check(sex in('男','女')),
cardId  char(18)  not null);

purchase:

create table purchase(customerId number(8) references customer(customerId),
goodsId char(8) references goods(goodsId),
nums number(2) check (nums  between 1 and 30));

如果在建表时忘记建立必要的约束,则可以在建表后使用alter table命令为表增加约束。但是要注意:增加not null 约束时,需要使用modify,其他为add选项。

 

 1)客户商品名不能为空:alter table goods modify  goodsName not null;

 2)地址为‘东城、朝阳、海淀、西城’:alter table customer add constraint addresscheck check (address in ('朝阳','西城'));

 3)身份证不能重复:alter table customer add constraint cardunique unique(cardId)

删除约束:alter table 表名 drop constraint  约束名称

删除主键:alter table 表名 drop  primary key  cascade;

数据字典视图显示约束:user_constraints、user_cons_columns

表级定义和列级定义是没有差异的,只是书写方式的不同 。

索引:索引是为了提高速度,抽象理解为一个索引表(目录)

列上加索引:

 单列索引:create index 索引名  on  表名(列名)

   create index nameIndex on customer(name)

 复合索引:create index 索引名  on  表名(列名1,列名2)

建立索引原则:

 1)在大表上建立索引才有意义

 2)在where子句中或者连接条件上经常引用的列上建立有意义

 3)多级索引不要超过4层

索引的缺点:

1.建立索引占用表的1.2倍的硬盘和内存

2.更新数据的时候,系统必须要有额外的时间来同时对索引进行更新。

user_indexs显示当前用户的索引信息;dba_indexs用于显示数据库所有的索引信息;user_ind_columns可以显示索引列的信息。

posted @ 2019-12-30 21:30  小熊尤里  阅读(170)  评论(0编辑  收藏  举报