Oracle外鍵(Foreign Key)用法詳解(一)
演示如何在Oracle數據庫中使用外鍵
1)在Oracle數據庫中,外鍵是用來實現參照完整性的方法之一。打個形象的比喻,外鍵是指定義外鍵的表的列的值必須在另一個表中出現。
2)被參照的表稱之為父表(parent table),創建外鍵的表稱之為子表(child table)。子表中的外鍵關聯了父表中的主鍵。
3)外鍵可以在創建表時定義或者通過ALTER TABLE語句創建。
語法:
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) );
語法:
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);-------------------------------------------------------------------------------------------------------------------
如果您們在嘗試的過程中遇到什麼問題或者我的代碼有錯誤的地方,請給予指正,非常感謝!
聯系方式:[email protected]
版權@:轉載請標明出處!