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