我正在尝试创建表格CanTeach
,但出现错误ERROR 1005 (HY000): Can't create table 'mydb'.'CanTeach' (errno: 150 "Foreign key constraint is incorrectly formed").
最终,我正在尝试创建一个“教师可以教的课程”表格,以验证他们为提供该课程的部门工作。
CREATE TABLE Department (
Name varchar(255) NOT NULL PRIMARY KEY
);
CREATE TABLE Person (
SSN CHAR(9) NOT NULL PRIMARY KEY,
LastName varchar(255),
FirstName varchar(255)
);
CREATE TABLE Professor (
SSN CHAR(9),
PRIMARY KEY(SSN),
FOREIGN KEY (SSN) REFERENCES Person(SSN)
);
CREATE TABLE WorksFOR (
SSN CHAR(9),
Salary float NOT NULL,
DepName varchar(255),
CONSTRAINT WorksFor_Salary CHECK (Salary>=0),
CONSTRAINT WorksFor_pk PRIMARY KEY(SSN,DepName),
CONSTRAINT WorksFor_ssn_fk FOREIGN KEY(SSN) REFERENCES Professor(SSN),
CONSTRAINT WorksFor_dep_fk FOREIGN KEY(DepName) REFERENCES Department(Name)
);
CREATE TABLE Course (
CourseDepartment varchar(255) NOT NULL,
CourseNumber varchar(8) NOT NULL,
CONSTRAINT Course_pk PRIMARY KEY(CourseDepartment,CourseNumber),
FOREIGN KEY(CourseDepartment) REFERENCES Department(Name)
);
CREATE TABLE CanTeach (
SSN CHAR(9) NOT NULL,
Department varchar(255) NOT NULL,
CourseNum varchar(8) NOT NULL,
CONSTRAINT CanTeach_pk PRIMARY KEY(SSN,Department,CourseNum),
FOREIGN KEY(SSN,Department) REFERENCES WorksFor(SSN,DepName),
FOREIGN KEY(Department,CourseNum) REFERENCES Course(CourseDepartment,CourseNumber)
);