search

Home  >  Q&A  >  body text

MySQL FOREIGN KEY constraint error

Create table Student
(
    Sno varchar(7) primary key,
    Sname varchar(10) not null,
    Ssex char (2) check(Ssex=‘男’or Ssex=’女’),
    Sage int check(Sage between 15 and 45),
    Sdept varchar(20) default ‘计算机系’
);
Create table course
(
    Cno varchar(10) primary key,
    Cname varchar(20) not null,
    Ccredit int check(Sctedit>0),
    Semester int check(Semester>0),
    Period int check(Period>0)
);
Create table SC
(
    Sno varchar(7) foreign key references student(Sno),
    Cno varchar(10) foreign key references course(Cno),
    Grade int check(Grade between 0 and 100),
    Primary key (Sno,Cno)
);

The first two can successfully create the table, but the third one reports an error:

Change the third one:

Create table SC
(
    Sno varchar(7),
    Cno varchar(10),
    Grade int check(Grade between 0 and 100),
    foreign key (Sno) references student(Sno),
    foreign key (Cno) references course(Cno),
    Primary key (Sno,Cno),
);

Still reporting an error:

Please answer, thank you boss!

巴扎黑巴扎黑2747 days ago547

reply all(1)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-05-18 10:47:13

    The way to create a foreign key is wrong,

    reply
    0
  • Cancelreply