1、创建表时直接创建外键约束
create table books(洞拍bookid number(10) not null primary key,
bookName varchar2(20) not null,
price number(10,2),
categoryId number(10) not null references Category(id) --外键约束
)
2、先创建表,表创建成功后,单独添加外键约束
create table books(bookid 弯颤唯number(10) not null primary key,
bookName varchar2(20) not null,
price 埋培number(10,2),
categoryId number(10) not null
)
ALTER TABLE books ADD CONSTRAINT FK_Book_categoryid FOREIGN KEY(categoryId ) REFERENCES Category(id)
--使用前禅谨表级慧基约束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 SCOTT.DEPT(DEPTNO NUMBER(2,0) PARIMARY KEY,
DNAME VARCHAR2(14),
LOC 空谨VARCHAR2(13))
创建副表及外键此汪:
CREATE TABLE EMP(EMPNO NUMBER(4,0) PRIMARY KEY,
ENAME VARCHAR2(10), 森亏仔
JOB VARCHAR2(9),
MGR NUMBER(4,0),
HIREDATE DATE,
SAL NUMBER(7,2),
COMM NUMBER(7,2),
DEPTNO NUMBER(2,0),
CONSTRAINT FK_DEPTNO FOREIGN KEY (DEPTNO) REFERENCES DEPT (DEPTNO))
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)