错误消息:#1215 - 无法添加外键约束
你好我不能创建表外键...怎么做...我有两个表..
第一个表有两个主键,第二个表是1个主键...
第一个表是
courseid varchar(5)
和courseyear 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`)
)
答案 0 :(得分:2)
这是样本SQLFiddle
您必须在primary key (subj_id)
表
studentload
在你的foriegn关系中,courseid不是tablename。它应该是
"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)
);
答案 1 :(得分:1)
您使用过“引用courseid
(courseid
,courseyear
)”。 courseid不是你的表名。它应该是“引用course
(courseid
,courseyear
)”
答案 2 :(得分:0)
有时是由于表创建的顺序。确保首先创建非外键表。