我正在尝试使用SQL声明一个FOREIGN KEY,但我总是遇到这个错误:
FOREIGN KEY (Dno) REFERENCES DEPARTMENT (Dnumber))
第14行的错误:ORA-00942:表或视图不存在
FOREIGN KEY (Mgr_ssn) REFERENCES EMPLOYEE(Ssn))
*
第8行的错误:ORA-00942:表或视图不存在
这是我正在使用的代码:
CREATE TABLE employee (fname VARCHAR (15) NOT NULL,
minit CHAR,
lname VARCHAR (15) NOT NULL,
ssn CHAR (9) NOT NULL,
bdate DATE,
address VARCHAR (30),
sex CHAR,
salary DECIMAL (10, 2),
super_ssn CHAR (9),
dno INT NOT NULL,
PRIMARY KEY (ssn),
FOREIGN KEY (super_ssn) REFERENCES employee (ssn),
FOREIGN KEY (dno) REFERENCES department (dnumber));
CREATE TABLE department (dname VARCHAR (15) NOT NULL,
dnumber INT NOT NULL,
mgr_ssn CHAR (9) NOT NULL,
mgr_start_date DATE,
PRIMARY KEY (dnumber),
UNIQUE (dname),
FOREIGN KEY (mgr_ssn) REFERENCES employee (ssn));
答案 0 :(得分:1)
由于您的employee表create语句具有对department表的引用,因此您需要确保首先创建department表。但是,作为create department表脚本的一部分,您可以引用employee表。循环引用啊!
幸运的是,您可以创建与创建表脚本分开的约束,这是您在这种情况下必须执行的操作,例如:
CREATE TABLE employee (fname VARCHAR (15) NOT NULL,
minit CHAR,
lname VARCHAR (15) NOT NULL,
ssn CHAR (9) NOT NULL,
bdate DATE,
address VARCHAR (30),
sex CHAR,
salary DECIMAL (10, 2),
super_ssn CHAR (9),
dno INT NOT NULL,
PRIMARY KEY (ssn),
FOREIGN KEY (super_ssn) REFERENCES employee (ssn));
CREATE TABLE department (dname VARCHAR (15) NOT NULL,
dnumber INT NOT NULL,
mgr_ssn CHAR (9) NOT NULL,
mgr_start_date DATE,
PRIMARY KEY (dnumber),
UNIQUE (dname),
FOREIGN KEY (mgr_ssn) REFERENCES employee (ssn));
alter table employee add constraint emp_dept_fk FOREIGN KEY (dno) REFERENCES department (dnumber);