1,約束的分類。
約束分成5類:1. not null,2.primary key,3.check,4.unique,5.foreign key。
1.1 not null約束
預設情況下,所有列的值都可以包含null值,當在列上定義not null約束後,列上面就必須得有值。not null約束還常常與其它的約束一起組合起來使用,比如與unique約束一起使用,就可以保證新插入的列的資料不會與已經存在的資料發生衝突。需要在相當的列上面建立索引的時候,建議也在相關的列上面增加上not null約束,因為索引不會存放null記錄。
1.2 primary key約束
主鍵約束其實就是not null約束與unique約束的一個組合,用來保證行記錄的唯一,不重複性。每張表只能有一個主鍵約束,在表設計的時候,我們一般都每張表上面都要有主鍵約束。在建立主鍵的時候會自己的建立相應約束名的索引,在選擇主鍵約束的列的時候可以參考下面指導:
1.選擇sequence的列做為主鍵。
2.選擇列的值是唯一的,並且沒有null值的列。
3.主鍵的更一般不會發生修改,也僅僅用於標識行的唯一性,不用於其它的目的。
4.主鍵的列盡量選擇值比較短的值或者是number的值。
1.3 unique約束
unique約束是保證值的記錄不會出現相同的值,但是noll值不受許可權,建立unique約束的時候,會自己建立約束名的索引。
1.4 check約束
檢查約束用於檢查值在插入時是否滿足指定的條件,比如值要求大於10小於100.
1.5 foreign key約束
當2個表,當A表中的列的值必須在B表中的列的值時候,可以定義外鍵約束。父表相關的值上面有主鍵或者唯一性限制式。不過很多公司要求不能使用外鍵,讓開發自己用程式來判斷。
2,約束的定義
約束可以在表建立的時候指定,也可以在表建立完成後通過alter命令來建立,下面是每一種約束建立的文法。
- 2.1 not null約束
-
- create table test_cons (id number constraint cons_test_cons_id_nonull not null);
-
- create table test_cons_1(id number not null);
-
- alter table test_cons_2 modify id not null;
-
- 2.2 primary key
-
- create table test_cons_1 (id number primary key);
-
- create table test_cons_2 (id number constraint cons_2 primary key);
-
- create table test_cons_3 (id number,constraint cons_3 primary key(id));
-
- create table test_cons_4 (id number);
-
- alter table test_cons_4 add constraint cons_4 primary key(id);
-
- 2.3 unique
-
- create table test_cons_1 (id number unique);
-
- create table test_cons_2 (id number constraint cons_2 unique);
-
- create table test_cons_3 (id number,constraint cons_3 unique(id));
-
- create table test_cons_4 (id number);
-
- alter table test_cons_4 add constraint cons_4 unique(id);
-
- 2.4 check
-
- create table test_cons_1 (id number check (id > 10 and id <100));
-
- create table test_cons_2 (id number constraint cons_2 check (id > 10 and id <100));
-
- create table test_cons_3 (id number,constraint cons_3 check (id > 10 and id <100));
-
- create table test_cons_4 (id number);
-
- alter table test_cons_4 add constraint cons_4 check (id > 10 and id <100);
-
- 2.5 外鍵約束
-
- create table test_cons_1 (id number,constraint cons_1 foreign key (id) references test_cons(id));
-
- alter table test_cons_4 add constraint cons_4 foreign key (id) references test_cons(id);