首页 > 代码库 > Oracle之外键(Foreign Key)用法详解(一)

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);


-------------------------------------------------------------------------------------------------------------------

如果您们在尝试的过程中遇到什么问题或者我的代码有错误的地方,请给予指正,非常感谢!

联系方式:david.louis.tian@outlook.com

版权@:转载请标明出处!
--------------------------------------------------------------------------------------------------------------------

Oracle之外键(Foreign Key)用法详解(一)