A case of MySQL ERROR 1215 (HY000)

create table pcourse(
cno char(9),
cpno char(9),
primary key(cno,cpno),
foreign key(cno) references course(cno),
foreign key(cpno) references course(cno)
);
ERROR 1215 (HY000): Cannot add foreign key constraint


Xidian database computer operation. This foreign key just can't be added. Before student and course had Chinese data, both set character_set_server and set character_set_database = utf8, but you still need to add default charset = utf8 after defining the table when creating a table. So it should be like this:
create table pcourse(
cno char(9),
cpno char(9),
primary key(cno,cpno),
foreign key(cno) references course(cno),
foreign key(cpno) references course(cno)
) default charset=utf8;
Note that there must be a space before the defualt, otherwise ERROR 1215 (HY000): Cannot add foreign key constraint.

A foreign key is not required when creating a table course:
create table course(
cno char(9),
cname char(48) not null,
ccredit int,
primary key (cno)
);
Warning | 1265 | Data truncated for column 'cname' at Row 1
is also solved by setting default charset=utf8.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325250875&siteId=291194637