2016-04-26 56 views
1

我在教程中的练习任务上使用了MySQL,但是我在创建一个错误“不正确的约束”表时遇到了问题。MySQL - errno 150:“外键约束不正确”

请看看,并建议我如何解决它。谢谢!

* A当然,产品是在特定的学期 提供的课程*学生将在课程祭,不是课程 *注册讲师被分配到课程祭,不是课程

CREATE TABLE `students` (
    `student_id` char(8) NOT NULL, 
    `max_load` tinyint(4) NOT NULL, 
    PRIMARY KEY (`student_id`) 
) 
CREATE TABLE `courses` (
`course_code` char(8) NOT NULL, 
`course_title` varchar(100) NOT NULL, 
PRIMARY KEY (`course_code`) 
) 
CREATE TABLE `lecturers` (
    `lecturer_id` char(8) NOT NULL, 
    `lecturer_name` varchar(50) NOT NULL, 
    PRIMARY KEY (`lecturer_id`) 
) 

CREATE TABLE `course_offerings` (
    `course_code` char(8) NOT NULL, 
    `semester` tinyint(4) NOT NULL, 
    `year` year(4) NOT NULL, 
    `lecturer_id` char(8) NOT NULL, 
    PRIMARY KEY (`course_code`,`semester`,`year`), 
    FOREIGN KEY (`course_code`) REFERENCES `courses` (`course_code`), 
    FOREIGN KEY (`lecturer_id`) REFERENCES `lecturers` (`lecturer_id`) 
) 

CREATE TABLE `enrolment` (
`student_id` char(8) NOT NULL, 
`course_code` char(8) NOT NULL, 
`semester` tinyint(4) NOT NULL, 
`year` year(4) NOT NULL, 
PRIMARY KEY (`student_id`,`course_code`,`semester`,`year`), 
FOREIGN KEY (`student_id`) REFERENCES students(`student_id`), 
FOREIGN KEY (`course_code`) REFERENCES course_offerings(`course_code`), 
FOREIGN KEY (`semester`) REFERENCES course_offerings(`semester`), 
FOREIGN KEY (`year`) REFERENCES course_offerings(`year`) 
) 

回答

1

您是否试图在enrolment上使用复合外键?如果是这样的话,以下可能就是你想要的。

CREATE TABLE `enrolment` (
    `student_id` char(8) NOT NULL, 
    `course_code` char(8) NOT NULL, 
    `semester` tinyint(4) NOT NULL, 
    `year` year(4) NOT NULL, 
PRIMARY KEY (`student_id`,`course_code`,`semester`,`year`), 
FOREIGN KEY (`student_id`) 
    REFERENCES students(`student_id`), 
FOREIGN KEY (`course_code`, `semester`, `year`) 
    REFERENCES course_offerings(`course_code`, `semester`, `year`)) 

我建议你创建一个course_offerings列id并使其主键,保持course_code,学期和年度合并唯一键。使用此id作为外键,因此您将需要1列而不是3列。

+1

非常感谢,我会按照你的建议。 –

0

您需要检查你列的类型源和目标表之间 semester TINYINT NOT NULL, year年NOT NULL, VS semester TINYINT(4)NOT NULL, year年(4)NOT NUL L,

+0

它没有帮助,甚至后,我检查所有。然而,年份的长度(4),(8)和tinyint ...是由向导自动添加的,因为它们是这些类型的默认长度。 –

-1

这个怎么样?

ALTER TABLE `kategori_transportasi` ADD FOREIGN KEY (`no_ktp_pemesan`) REFERENCES `tbl_daftar_customer` (
`no_ktp_pemesan`); 

MySQL表示:文件

#1005 - Can't create table `kuda_express`.`#sql-d64_216` (errno: 150 "Foreign key constraint is incorrectly formed") (Details…) 
相关问题