天天看點

Oracle資料庫操作大全(十三)——限制,索引

索引——在查詢表慢的時候,說先要想到建索引

維護資料的完整性:

Oracle資料庫操作大全(十三)——限制,索引

***限制:

Oracle資料庫操作大全(十三)——限制,索引
Oracle資料庫操作大全(十三)——限制,索引
Oracle資料庫操作大全(十三)——限制,索引

經典案例:

Oracle資料庫操作大全(十三)——限制,索引

建表:

 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)

   );

Oracle資料庫操作大全(十三)——限制,索引

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 ('東城','西城'));//增加客戶住址限制

Oracle資料庫操作大全(十三)——限制,索引

顯示限制資訊:

Oracle資料庫操作大全(十三)——限制,索引

表級定義和列級定義:

Oracle資料庫操作大全(十三)——限制,索引

管理索引:

Oracle資料庫操作大全(十三)——限制,索引

為什麼添加索引會加快查詢速度?

****一個圖書館書圖書沒有進行分類存放

****一個圖書館書圖書進行按類别(且按序)存放,

      去借書可先在電腦查詢書的具體位置,可快速的找到要看的書。(電腦相當于建立的索引)

索引的建立:

***簡單索引建立

    create index nameIndex on customer(name);//nameIndex為索引名,自定義;customer為表名,name為列

***單列索引

Oracle資料庫操作大全(十三)——限制,索引

***複合索引

Oracle資料庫操作大全(十三)——限制,索引

    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語句為從後往前掃描)

索引使用原則:

Oracle資料庫操作大全(十三)——限制,索引