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) );
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) );
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);
-------------------------------------------------------------------------------------------------------------------
假設您們在嘗試的過程中遇到什么問題或者我的代碼有錯誤的地方。請給予指正,很感謝!
聯系方式:david.louis.tian@outlook.com
版權@:轉載請標明出處!
版權聲明:本文博主原創文章,博客,未經同意不得轉載。