標籤:oracle 外鍵 foreign key 約束 外鍵約束
Oracle外鍵(Foreign Key)用法詳解(一)
1.目標
示範如何在Oracle資料庫中使用外鍵
2.什麼是外鍵?
1)在Oracle資料庫中,外鍵是用來實現參照完整性的方法之一。打個形象的比喻,外鍵是指定義外鍵的表的列的值必須在另一個表中出現。
2)被參照的表稱之為父表(parent table),建立外鍵的表稱之為子表(child table)。子表中的外部索引鍵關聯了父表中的主鍵。
3)外鍵可以在建立表時定義或者通過ALTER TABLE語句建立。
3.建立表時定義外鍵
文法:
CREATE TABLE table_name( column1 datatype null/not null, column2 datatype null/not null, ... CONSTRAINT fk_column FOREIGN KEY (column1,column2,... column_n) REFERENCES parent_table (column1,column2,...column_n));
樣本1:基於單列的外鍵
create table tb_supplier( supplier_id number not null, supplier_name varchar2(50) not null, contact_name varchar2(50), CONSTRAINT pk_supplier PRIMARY KEY (supplier_id));create table tb_products( product_id number not null, product_name varchar2(100), supplier_id number not null, constraint fk_products_supplier foreign key (supplier_id) references tb_supplier(supplier_id));
樣本2:基於多列的外鍵
drop table TB_PRODUCTS;drop table TB_SUPPLIER;create table tb_supplier( supplier_id number not null, supplier_name varchar2(50) not null, contact_name varchar2(50), CONSTRAINT pk_supplier PRIMARY KEY (supplier_id,supplier_name));create table tb_products( product_id number not null, product_name varchar2(100), supplier_name varchar2(50), supplier_id number not null, constraint fk_products_supplier foreign key (supplier_id,supplier_name) references tb_supplier(supplier_id,supplier_name));
4.使用ALTER TABLE命令建立外鍵
文法:
ALTER TABLE table_name ADD CONSTRAINT constraint_name FOREIGN KEY (column1, column2,...column_n) REFERENCES parent_table (column1,column2,...column_n);
樣本:
drop table TB_PRODUCTS;drop table TB_SUPPLIER;create table tb_supplier( supplier_id number not null, supplier_name varchar2(50) not null, contact_name varchar2(50), CONSTRAINT pk_supplier PRIMARY KEY (supplier_id,supplier_name));create table tb_products( product_id number not null, product_name varchar2(100), supplier_name varchar2(50), supplier_id number not null);--使用alter table建立外鍵 alter table tb_products add constraint fk_products_supplier foreign key (supplier_id,supplier_name) references tb_supplier(supplier_id,supplier_name);
-------------------------------------------------------------------------------------------------------------------
如果您們在嘗試的過程中遇到什麼問題或者My Code有錯誤的地方,請給予指正,非常感謝!
連絡方式:[email protected]
著作權@:轉載請標明出處!
--------------------------------------------------------------------------------------------------------------------
Oracle之外鍵(Foreign Key)用法詳解(一)