Oracle外部キー(Foreign Key)の使用に関する詳細な説明(一)

2901 ワード

Oracle外部キー(Foreign Key)の使用に関する詳細な説明(一)
1.目標
Oracleの外部キー・データベースの使用方法の説明
2.外部キーとは?
1)Oracleデータベースでは、外部キーは参照整合性を実現するためのメソッドの1つです.イメージの比喩をする.外部キーとは、外部キーを定義するテーブルのカラムの値が、別のテーブルに表示される必要があることを意味します.
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);

-------------------------------------------------------------------------------------------------------------------
試している間に何か問題があったり、私のコードに間違いがあったりしたとします.指摘してください.ありがとうございます.連絡先:[email protected]転載は出典を明記してください!
--------------------------------------------------------------------------------------------------------------------
本文のブロガーのオリジナルの文章、ブログ、同意を得ないで転載してはいけません.