0

错误消息:#1215 - 无法添加外键约束

你好我不能创建表外键...怎么做...我有两个表..第一个表有两个主键然后第二个表是一个主键...第一个表是 courseid varchar(5) andcourseyear int 和第二个是subj_id varchar(5)

create table studentload(
student_id varchar(11) not null,
courseid varchar(5) not null,
courseyear int not null,
subj_id varchar(5) not null,
foreign key (courseid,courseyear) references course(courseid,courseyear),
foreign key (subj_id) references subject(subj_id)
)

编辑

这是我已经插入的所有表格

CREATE TABLE IF NOT EXISTS `course` (
  `courseid` varchar(5) NOT NULL,
  `courseyear` int(11) NOT NULL,
  `coursedesc` varchar(50),
  `subj_id` varchar(5) NOT NULL,
  PRIMARY KEY (`courseid`,`courseyear`)
) 


CREATE TABLE IF NOT EXISTS `subject` (
  `subj_id` varchar(5) NOT NULL,
  `subj_name` varchar(50) NOT NULL,
  `courseid` varchar(5),
  `courseyear` int(11),
  foreign key (`courseid`,`courseyear`) references `courseid` (`courseid`,`courseyear`)
) 
4

3 回答 3

2

这是示例SQLFiddle

您必须primary key (subj_id)studentload表格中添加

在您的外交关系中, courseid 不是表名。它应该是

"references course(courseid,courseyear)"

CREATE TABLE IF NOT EXISTS `course` (
  `courseid` varchar(5) NOT NULL,
  `courseyear` int(11) NOT NULL,
  `coursedesc` varchar(50),
  `subj_id` varchar(5) NOT NULL,
  PRIMARY KEY (`courseid`,`courseyear`)
); 


CREATE TABLE IF NOT EXISTS `subject` (
  `subj_id` varchar(5) NOT NULL,
  `subj_name` varchar(50) NOT NULL,
  `courseid` varchar(5),
  `courseyear` int(11),
  foreign key (`courseid`,`courseyear`) references `course` (`courseid`,`courseyear`),
  primary key (`subj_id`)
);

create table studentload(
  student_id varchar(11) not null,
  courseid varchar(5) not null,
  courseyear int not null,
  subj_id varchar(5) not null,
  foreign key (courseid,courseyear) references course(courseid,courseyear),
  foreign key (subj_id) references subject(subj_id)
);
于 2013-09-06T05:27:36.560 回答
1

您使用了“引用courseid( courseid, courseyear) ”。courseid 不是您的表名。它应该是“引用coursecourseidcourseyear)”

于 2013-09-06T05:28:09.787 回答
0

有时这是由于表创建的顺序。确保首先创建非外键表。

于 2020-06-13T18:27:44.583 回答