2012-11-06 34 views
1

我試圖設置一個創建5個表的MySQL腳本。在三個表,有一個FOREIGN KEY,併爲三人都出現了同樣的錯誤:「在表中不存在鍵列」當試圖定義FOREIGN KEY

Error Code: 1072. Key column ... doesn't exist in table 

而...是GebaeudeDept_NameMat_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工作,並且清楚地看到創建的表格,並將特定列標記爲主鍵!

回答

6

你做錯了,看看這個例子

http://www.sqlfiddle.com/#!2/a86cf

您的FK行應該更多這樣的:

FOREIGN KEY (field_that_will_be_Fk) REFERENCES Table_to_reference (field_to_reference)

IE =

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; 
1

您必須先在每個表中創建列,然後才能將它們限制爲外鍵。

請參閱此鏈接以供參考:Link

相關問題