我在这里有一个关于我试图实施的数据库的快速问题。我已经提到了几个与我类似的问题,但他们并没有完全回答我的具体问题。
我使用SQL比较新,我不久前已经上了一堂课,所以我可能只需要一个哈!这里有一种复习。
当我尝试使用MySQL构建这个数据库时,由于错误说"错误代码1215,我无法创建任何表,无法添加外键约束"
我只是错过了一些明显的东西吗?
下面是我的SQL:
create database emp;
use emp;
select database ();
create table employee
(Fname varchar (15),
Minit varchar (1),
Lname varchar (15),
Ssn int (9) not null,
Bdate varchar (10),
Address varchar (40),
Sex varchar (1),
Salary varchar (10),
Super_ssn varchar (9),
Dno int (1),
primary key(Ssn),
foreign key(Super_ssn) references employee(Ssn),
foreign key(Dno) references department(Dnumber)
)
Engine=INNODB;
create table department
(Dname varchar (15),
Dnumber int (1) not null,
Mgr_ssn int (9),
Mgr_start_date varchar (15),
primary key(Dnumber),
foreign key(Mgr_ssn) references employee (Ssn)
)
Engine=INNODB;
create table dept_locations
(Dnumber int (1) not null,
Dlocation varchar (15) not null,
primary key(Dnumber, Dlocation),
foreign key(Dnumber) references department(Dnumber)
)
Engine=INNODB;
create table project
(Pname varchar (15),
Pnumber int (3) not null,
Plocation varchar (15),
Dnum int (1),
primary key(Pnumber),
foreign key(Dnum) references department(Dnumber)
)
Engine=INNODB;
create table works_on
(Essn int (9) not null,
Pno int (3) not null,
hours float (4),
primary key(Essn, Pno),
foreign key (Essn) references employee(Ssn),
foreign key(Pno) references project (Pnumber)
)
Engine=INNODB;
create table dependent
(Essn int (9) not null,
Dependent_name varchar (15) not null,
Sex varchar (1),
Bdate varchar (10),
Relationship varchar (10),
primary key(Essn, Dependent_Name),
foreign key (Essn) references employee(Ssn)
)
Engine=INNODB;
答案 0 :(得分:2)
在创建另一个表之前,无法创建引用另一个表的外键。因此,在创建employee
表之前,department
中的外键不能引用department
。但由于department
表具有引用employee
的外键,因此您也无法以相反的顺序创建它们。
创建表时,请省略引用尚未创建的表的外键,然后使用ALTER TABLE
添加它们。
create table employee
(Fname varchar (15),
Minit varchar (1),
Lname varchar (15),
Ssn int (9) not null,
Bdate varchar (10),
Address varchar (40),
Sex varchar (1),
Salary varchar (10),
Super_ssn varchar (9),
Dno int (1),
primary key(Ssn),
foreign key(Super_ssn) references employee(Ssn),
);
create table department
(Dname varchar (15),
Dnumber int (1) not null,
Mgr_ssn int (9),
Mgr_start_date varchar (15),
primary key(Dnumber),
foreign key(Mgr_ssn) references employee (Ssn)
);
alter table employee add constraint foreign key (Dno) references department(Dnumber);