數據庫:唯一性約束_alternate key(替換鍵) mySQL Oracle 數據庫 ak 唯一性約束
數據庫:唯一性約束
所謂唯一性約束(unique constraint)不過是數據表內替代鍵的另一個名稱而已。替代鍵(alternate key)可以是數據表內不作為主鍵的其他任何列,只要該鍵對該數據表唯一即可。換句話說,在唯一列內不允許出現數據重復的現象。比方說,你可以用車輛識別代號(VIN)作為汽車(Automobile)數據表的替代鍵,在汽車數據表里,主鍵是汽車識別號(Automobile Identification),這是一種由系統自動生成的ID。你可以在汽車表內對VIN施加唯一性約束,同時再創建一個需要VIN的表。在這個新表內可以聲明外鍵指向汽車表。這樣,只要汽車表內有VIN輸入數據庫就會檢驗VIN輸入結果。這就是保證數據庫內數據完整性的另一種有效的措施。
create table parent
(parent_id int not null,????? -- Primary key
parent_alternate_key int not null,???? -- Alternate key
parent_col1 int null,
parent_col2 int null,
constraint pk_parent_id primary key (parent_id),
constraint ak_parent_alternate_key unique_
(parent_id, parent_alternate_key)
使用約束:
create table child2
(child2_parent_id int not null,???? -- Primary key/Foreign key
child2_id int not null,???? -- Primary key
child2_col1 int null,
child2_parent_alternate_key int not null,? -- Foreign key
constraint pk_child2 primary key (child2_parent_id, child2_id),
constraint fk_child2_parent foreign key (child2_parent_id)
references dbo.parent(parent_id),
constraint fk_pk_ak_child2_parent foreign key _
(child2_parent_id, child2_parent_alternate_key) _
references dbo.parent(parent_id, parent_alternate_key)
primary key 與UNIQUE的區別
1.一個基本表中只能定義一個primary key,但可以定義多個UNIQUE的約束
2.指定primary key的一個列或多個列的組合都不能為NULL,而UNIQUE所約束的唯一鍵則允許為空
3.不能為一個列或多個列既定義primary key,又定義UNIQUE約束
MYSQL目前不支持外鍵,其理由如下:
1.外鍵使生活更復雜,因為外鍵的定義必須存儲在一個數據庫中并且實現他們將破壞使用能被移動、拷貝和刪除文件的全部“好方法”。
2.速度影響對INSERT和UPDATE語句是可怕的,并且在這種情況下幾乎所有的FOREIGN KEY檢查都是無用的,因為不管怎樣你通常以正確的順序在正確的表中插入記錄。
3.當更新一張表時,也有在許多表上保存鎖的需求,因為副作用可以串聯通過全部數據庫。首先從一張表中刪除記錄并且隨后從其他表中刪除他們,這更快。
4.你再也不可以通過做一個全面的表刪除并隨后恢復所有的記錄的方法來恢復一張表(從新來源或從一個備份)。
5.如果你有外鍵,你不能傾倒和恢復表,除非你以一個非常特定的做這些。
6.很容易做一個“允許的”的循環定義使得不可能用一個單個create語句重建每一個表,就算定義可行又可用。