我正在尝试运行以下SQL(在MySQL服务器上)创建语句:
Create table if not exists Employees (id integer primary key, name char(40) not null, department char(40) not null, salary int not null, phone char(40) not null)
Create table if not exists Managers (mid integer primary key, name char(40) not null, department char(40) not null, salary integer not null, phone char(40) not null)
Create table if not exists Departments (did integer primary key, dname char(40) not null, numberofworkers integer not null, manager char(40) not null)
Create table if not exists works_in (id integer, did integer, primary key (id, did), foreign key Employees(id) references Employees, foreign key Departments(did) references Departments)
Create table if not exists Management (mid integer, did integer, primary key (mid, did), foreign key Managers(mid) references Managers, foreign key Departments(did) references Departments)
一切都很好,除了最后两行,我得到了:
ERROR 1215 (HY000): Cannot add foreign key constraint
我尝试运行SHOW ENGINE INNODB STATUS;
来查看问题所在,并给出了:
Error in foreign key constraint of table project/works_in:
foreign key Employees(id) references Employees, foreign key Departments(did) references Departments):
Syntax error close to:
, foreign key Departments(did) references Departments)
但无论如何这无济于事。我尝试检查其他类似的问题,但大多数人建议列应该是相同的类型,这已经是这种情况了。
为什么我收到此错误?
答案 0 :(得分:2)
foreign key
声明的语法必须包含“其他”表中引用的键:
foreign key (did) references Departments (did)
foreign key (mid) references Managers(mid)
foreign key Departments (did) references Departments (did)
创建表格时,我强烈建议您将每一列放在一个单独的行中:
Create table if not exists works_in (
id integer,
did integer,
primary key (id, did),
foreign key (id) references Employees(id),
foreign key (did) references Departments(did)
);
你怎么能只阅读一个长期不间断的列定义流?