索引——在查询表慢的时候,说先要想到建索引
维护数据的完整性:
***约束:
经典案例:
建表:
create table goods(
goodsId char(8) primary key,--主键
goodsName varchar2(30),
unitprice number(10,2) check (unitprice>0),
category varchar2(8),
provider varchar2(30)
);
create table customer(customerId char(8) primary key,--主键
name varchar2(50) not null,
address varchar2(50),
email varchar2(50) unique,
sex char(2) default'男' check(sex in('男','女')),//sex默认为男,其只可在‘男’或‘女’范围内.
cardId char(18)
);
create table purchase(
customerId char(8) references customer(customerId),
goodsId char(8) references goods(goodsId),
nums number(10) check (nums between 1 and 30)
);
alter table goods modify goodsName not null;//修改表goods中goodsName字段使其不为空。
alter table customer add constraint aa unique(cardId);//增加身份证不为空,其中阴影标记为约束名自定义即可
alter table customer add constraint bb check (address in ('东城','西城'));//增加客户住址约束
显示约束信息:
表级定义和列级定义:
管理索引:
为什么添加索引会加快查询速度?
****一个图书馆书图书没有进行分类存放
****一个图书馆书图书进行按类别(且按序)存放,
去借书可先在电脑查询书的具体位置,可快速的找到要看的书。(电脑相当于建立的索引)
索引的建立:
***简单索引建立
create index nameIndex on customer(name);//nameIndex为索引名,自定义;customer为表名,name为列
***单列索引
***复合索引
create index emp_isx1 on emp(ename,job);//表示先按ename查询,然后按job查询
create index emp_isx2 on emp(job,ename,);//表示先按job查询,然后按ename查询
知识小提:
在利用select语句查询时,如:select * from customer where job='CLERK' and ename='SMITH';
一般把检索范围小(更容易检索出结果)的放在后(ename),比较大的放在前(job);(因为SQL语句为从后往前扫描)
索引使用原则: