尝试定义 FOREIGN KEY 时出现“表中不存在键列”
Posted
技术标签:
【中文标题】尝试定义 FOREIGN KEY 时出现“表中不存在键列”【英文标题】:"Key column doesn't exist in table" when trying to define FOREIGN KEY 【发布时间】:2012-11-06 19:16:26 【问题描述】:我正在尝试设置一个创建 5 个表的 mysql 脚本。在三个表中,有一个FOREIGN KEY
,并且对于所有三个表都会出现相同的错误:
Error Code: 1072. Key column ... doesn't exist in table
而 ... 是 Gebaeude
、Dept_Name
和 Mat_Nr
这是脚本
use cs261_24;
drop table if exists Professor;
drop table if exists Departement;
drop table if exists Gebaeude;
drop table if exists Student;
drop table if exists Pruefung;
CREATE TABLE Gebaeude (
Gebaeude VARCHAR(20) NOT NULL PRIMARY KEY,
Hauswart VARCHAR(20) NOT NULL,
Adresse VARCHAR(20) NOT NULL
)engine = innodb;
CREATE TABLE Professor (
P_ID INTEGER PRIMARY KEY CHECK (P_ID > 0),
P_Name VARCHAR(20) NOT NULL,
Dept_Name VARCHAR(20) NOT NULL,
Raum INTEGER UNIQUE CHECK (Raum > 0),
Tel INTEGER(10) UNIQUE CHECK (Tel > 210000000),
FOREIGN KEY (Gebaeude) REFERENCES Gebaeude (Gebaeude)
)engine = innodb;
CREATE TABLE Departement (
Dept_Name VARCHAR(20) NOT NULL PRIMARY KEY,
Vorsteher VARCHAR(20) NOT NULL
)engine = innodb;
CREATE TABLE Student (
Mat_Nr INTEGER(8) PRIMARY KEY CHECK (Mat_Nr > 0),
S_Name VARCHAR(20) NOT NULL,
Semester INTEGER CHECK(Semester > 0),
FOREIGN KEY (Dept_Name) REFERENCES Departement (Dept_Name)
)engine = innodb;
CREATE TABLE Pruefung (
Pr_ID INTEGER PRIMARY KEY CHECK(Pr_ID > 0),
Fach VARCHAR(20) NOT NULL,
Pruefer VARCHAR(20) NOT NULL,
Note FLOAT CHECK (Note >= 1 AND Note <= 6),
FOREIGN KEY (Mat_Nr) REFERENCES Student (Mat_Nr)
)engine = innodb;
为什么?我使用 MySQL Workbench,我清楚地看到创建的表,以及特定的列被标记为主键!
【问题讨论】:
【参考方案1】:你做错了,看看这个例子
http://www.sqlfiddle.com/#!2/a86cf
您的 FK 行应该更像这样:
FOREIGN KEY (field_that_will_be_Fk) REFERENCES Table_to_reference (field_to_reference)
I.E=
CREATE TABLE Gebaeude (
Gebaeude VARCHAR(20) NOT NULL PRIMARY KEY,
Hauswart VARCHAR(20) NOT NULL,
Adresse VARCHAR(20) NOT NULL
)engine = innodb;
CREATE TABLE Professor (
Gebaeude_FK varchar(20) NOT NULL,
P_ID INTEGER PRIMARY KEY CHECK (P_ID > 0),
P_Name VARCHAR(20) NOT NULL,
Dept_Name VARCHAR(20) NOT NULL,
Raum INTEGER UNIQUE CHECK (Raum > 0),
Tel INTEGER(10) UNIQUE CHECK (Tel > 210000000),
FOREIGN KEY (Gebaeude_FK) REFERENCES Gebaeude (Gebaeude)
)engine = innodb;
【讨论】:
【参考方案2】:您必须先在每个表中创建列,然后才能将它们限制为外键。
参考此链接:Link
【讨论】:
以上是关于尝试定义 FOREIGN KEY 时出现“表中不存在键列”的主要内容,如果未能解决你的问题,请参考以下文章
数据库添加外键错误:[Err] 1215 - Cannot add foreign key constraint 的解决
在 MYSQL 中声明 FOREIGN KEYS 时出现语法错误(使用 innoDB)
ERROR 1217 (23000): Cannot delete or update a parent row: a foreign key constraint fails
数据库添加数据报错:Cannot add or update a child row: a foreign key constraint fails