错误代码1215,无法添加外键约束

时间:2017-01-23 03:33:16

标签: mysql sql database

我在这里有一个关于我试图实施的数据库的快速问题。我已经提到了几个与我类似的问题,但他们并没有完全回答我的具体问题。

我使用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; 

1 个答案:

答案 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);