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) );
CREATE TABLE DEPT_LOCATIONS
( Dnumber INT NOT NULL,
Dlocation VARCHAR(15) NOT NULL,
PRIMARY KEY (Dnumber, Dlocation),
FOREIGN KEY (Dnumber) REFERENCES DEPARTMENT(Dnumber) );
CREATE TABLE PROJECT
( Pname VARCHAR(15) NOT NULL,
Pnumber INT NOT NULL,
Plocation VARCHAR(15),
Dnum INT NOT NULL,
PRIMARY KEY (Pnumber),
UNIQUE (Pname),
FOREIGN KEY (Dnum) REFERENCES DEPARTMENT(Dnumber) );
CREATE TABLE WORKS_ON
( Essn CHAR(9) NOT NULL,
Pno INT NOT NULL,
Hours DECIMAL(3,1) NOT NULL,
PRIMARY KEY (Essn, Pno),
FOREIGN KEY (Essn) REFERENCES EMPLOYEE(Ssn),
FOREIGN KEY (Pno) REFERENCES PROJECT(Pnumber) );
CREATE TABLE DEPENDENT
( Essn CHAR(9) NOT NULL,
Dependent_name VARCHAR(15) NOT NULL,
Sex CHAR,
Bdate DATE,
Relationship VARCHAR(8),
PRIMARY KEY (Essn, Dependent_name),
FOREIGN KEY (Essn) REFERENCES EMPLOYEE(Ssn) );
这里我无法创建任何表,因为每个表都使用外键约束引用其他表。所以请帮助我如何创建整个数据库。例如。如果我正在创建EMPLOYEE表,它正在搜索DEPARTMENT表并且不允许创建表,并且我尝试创建DEPARTMENT然后它再次搜索EMPLOYEE表而不允许创建表。
答案 0 :(得分:1)
只需在创建表格时单独添加外键,例如
ALTER TABLE EMPLOYEE ADD CONSTRAINT FK_EMPLOYEE_DEPARTMENT
FOREIGN KEY (Dno) REFERENCES DEPARTMENT(Dnumber);
答案 1 :(得分:1)
您可以尝试在没有外键约束的情况下创建和填充表,然后添加外键约束。
答案 2 :(得分:0)
一个简单的解决方案是从创建DEPARTMENT
表中删除FK到EMPLOYEE
(下面的一个)并创建所有表/模式。
FOREIGN KEY (Dno) REFERENCES DEPARTMENT(Dnumber)
然后,在EMPLOYEE
表上重新创建此FK
ALTER TABLE EMPLOYEE ADD CONSTRAINT fk_emp
FOREIGN KEY (Dno) REFERENCES DEPARTMENT(Dnumber);
查看成功的表格创建演示http://sqlfiddle.com/#!2/410ce