gpt4 book ai didi

MySQL-错误号 150 : "Foreign key constraint is incorrectly formed"

转载 作者:行者123 更新时间:2023-11-28 23:32:56 25 4
gpt4 key购买 nike

我在教程中的练习任务中使用 MySQL,但我在创建表时遇到问题,并出现错误“不正确的约束”。

请查看并建议我如何修复它。谢谢!

*类(class)是指在特定学期开设的类(class)*学生将参加类(class)设置,而不是类(class)*讲师被分配到类(class)设置,而不是类(class)

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

最佳答案

您是否尝试在 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 列。

关于MySQL-错误号 150 : "Foreign key constraint is incorrectly formed",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36875119/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com