Oracle 创建外键表
依次创建A、B、C三张表,C的ID字段为非空主键,
并被B表的ID字段作为外键关联,
而A的ID字段关联B的ID字段,
依赖关系为:A依赖B依赖C,
故创建先后为C—>B—>A
创建语句如下
#创建表C create table C( ID VARCHAR2(50) not null primary key, C1 VARCHAR2(50), C2 VARCHAR2(50) ); #创建表B #这种创建方法 create table B( ID VARCHAR2(50) not null primary key, B1 VARCHAR2(50), B2 VARCHAR2(50), CONSTRAINT FK_CID FOREIGN KEY (ID) REFERENCES C (ID) ); #CONSTRAINT FK_CID:外键名为FK_CID名字可以任意起,但最好有实际意义 #FOREIGN KEY (ID):指定本表的那个字段作为外键 #:REFERENCES C (ID):参照C表的ID字段作为外键关联 #等同于: create table B( ID VARCHAR2(50) not null REFERENCES C(ID) primary key, B1 VARCHAR2(50), B2 VARCHAR2(50) not null ); #创建表A create table A( ID VARCHAR2(50) not null primary key, A1 VARCHAR2(50), A2 VARCHAR2(50), CONSTRAINT FK_BID FOREIGN KEY (ID) REFERENCES B (ID) );
创建(插入)大量测试数据表
创建:
create table C1 as
select rownum as id,
to_char(sysdate + rownum/24/3600, 'yyyy-mm-dd hh24:mi:ss') as inc_datetime,
trunc(dbms_random.value(0, 100)) as random_id,
dbms_random.string('x', 20) random_string
from dual
connect by level <= 1000;
插入:
insert into "C1"
(ID, INC_DATETIME,RANDOM_ID,RANDOM_STRING)
select rownum as id,
to_char(sysdate + rownum / 24 / 3600, 'yyyy-mm-dd hh24:mi:ss') as inc_datetime,
trunc(dbms_random.value(0, 100)) as random_id,
dbms_random.string('x', 20) random_string
from dual
connect by level <= 1000;