MySQL - 错误150:“外键约束形成错误”

时间:2016-04-26 20:29:02

标签: mysql foreign-keys constraints

我在教程中的练习任务中使用MySQL,但是我在创建一个错误“错误约束”错误的表时遇到了问题。

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

*课程设置是在特定学期提供的课程 *学生将报名参加课程,而不是课程 *讲师被分配到课程,而不是课程

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`)
)

4 个答案:

答案 0 :(得分: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,学期和年份组合UNIQUE键。使用此id作为外键,因此您需要1列而不是3列。

答案 1 :(得分:0)

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

答案 2 :(得分:0)

如果您已定义关系并删除与另一个表有关系的表,则会出现此错误。然后尝试将已删除的表导入回来。enter image description here

您可以通过关联表的这些步骤删除关系,然后在导入表后创建关系

答案 3 :(得分:-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…)
相关问题