--使用表級約束
專業(yè)成都網(wǎng)站建設(shè)公司,做排名好的好網(wǎng)站,排在同行前面,為您帶來客戶和效益!創(chuàng)新互聯(lián)公司為您提供成都網(wǎng)站建設(shè),五站合一網(wǎng)站設(shè)計制作,服務(wù)好的網(wǎng)站設(shè)計公司,網(wǎng)站設(shè)計制作、成都網(wǎng)站制作負責任的成都網(wǎng)站制作公司!
CREATE TABLE table_name
(column_1 datatype ,
column_2 datatype ,
...
CONSTRAINT fk_column
FOREIGN KEY (column_1, column_i, ... column_n)
REFERENCES parent_table (column_1, column_i, ... column_n)
);
--使用列級約束
CREATE TABLE table_name
(column_1 datatype ,
column_2 datatype CONSTRAINT fk_column REFERENCES parent_table (column_name),
...
);
create table T (
A NUMBER(14) not null,
B VARCHAR2(11) not null,
C VARCHAR2(20) not null,
D VARCHAR2(60),
E VARCHAR2(20) not null,
F VARCHAR2(50) not null,
constraint pk$T primary key (A), -- 主鍵
constraint uk$T unique (B) -- 唯一鍵
);
create table U (
UA NUMBER(14) not null,
UB VARCHAR2(11) not null,
UC VARCHAR2(20) not null,
UD VARCHAR2(60),
UE VARCHAR2(20) not null,
UF VARCHAR2(50) not null,
constraint fk$U_UA foreign key (UA) references T(A) -- 外鍵 fk$U_UA 是外鍵名
);
主鍵:ALTER TABLE A ADD CONSTRAINT PK_XXX PRIMARY KEY (XXX)
外鍵;ALTER TABLE B ADD CONSTRAINT FK_YYY FOREIGN KEY(YYY) REFERENCES A(XXX)
B表的YYY字段 引用A表的XXX字段值域為自身值域
主鍵約束,外鍵約束就是這樣建立的
刪除約束: ALTER TABLE A DROP CONSTRAINT 約束名
create TABLE zhao(
id number primary key,
mingcheng nvarchar2(50),
neirong nvarchar2(50),
jiezhiriqi date,
zhuangtai nvarchar2(50)
);
create TABLE tou(
id number primary key,
zhao_id number,
toubiaoqiye nvarchar2(50),
biaoshuneirong nvarchar2(50),
toubiaoriqi date,
baojia number,
zhuangtai nvarchar2(50),
foreign KEY(zhao_id) REFERENCES zhao(id)
);
foreign key (zhao_id) references to zhao(id)
多了個to
create TABLE zhao(\x0d\x0a id number primary key,\x0d\x0a mingcheng nvarchar2(50),\x0d\x0a neirong nvarchar2(50),\x0d\x0a jiezhiriqi date,\x0d\x0a zhuangtai nvarchar2(50)\x0d\x0a);\x0d\x0acreate TABLE tou(\x0d\x0a id number primary key,\x0d\x0a zhao_id number,\x0d\x0a toubiaoqiye nvarchar2(50),\x0d\x0a biaoshuneirong nvarchar2(50),\x0d\x0a toubiaoriqi date,\x0d\x0a baojia number,\x0d\x0a zhuangtai nvarchar2(50),\x0d\x0a foreign KEY(zhao_id) REFERENCES zhao(id)\x0d\x0a);\x0d\x0aforeign key (zhao_id) references to zhao(id)\x0d\x0a多了個to
以oracle自帶的用戶scott為例。
create?table?dept(
deptno?number(2)?primary?key,?--deptno?為?dept表的主鍵
dname?varchar2(10),
loc?varchar2(9)
);
create?table?emp(
empno?number(4)?primary?key,?--empno?為?emp表的主鍵
ename?varchar2(10),
job?varchar2(9),
mgr?number(4),
hiredate?date,
sal?number(7,2),
comm?number(7,2),
deptno?number(2)?references?dept(deptno)?--dept表中deptno字段?為?emp表的外鍵
);