Mysql reports error 1215 (HY000)/ Cannot add foreign key constraint when creating table

1. Error prompt

ERROR 1215 (HY000): Cannot add foreign key constraint

2. Process description

1. First create the following table
#创建学生表 
Create TABLE Student
	(Sno CHAR(9) PRIMARY KEY not null,	/*列级完整性约束,Sno是主码*/
   Sname CHAR(20) not null,
   Ssex CHAR(2),
   Sage SMALLINT,
   Sdept CHAR(20)
  )ENGINE=InnoDB DEFAULT CHARSET=utf8;/*指定字符集的编码方式为utf8,以便后续插入汉字型元组数据*/
2. Then create the following table
#创建课程表
create table Course
	(Cno CHAR(4) PRIMARY KEY not null,	/*列级完整性约束,Sno是主码*/
   Cname char(40) NOT NULL,
   Cpno CHAR(4),										  /*Cpno是先修课*/
   Ccredit SMALLINT,
   FOREIGN KEY (Cpno) REFERENCES Course(Cno) /*表级完整性约束条件,Cpno是外码,被参照对象是Cource,被参照列是Cno*/
  )ENGINE=InnoDB DEFAULT CHARSET=utf8;
3. Then create the following table
#创建选课表
CREATE TABLE SC
	(Sno CHAR(9)  not null ,
   Cno CHAR(4)  not null ,
   Grade SMALLINT,
   primary key (sno,cno),
   foreign key (Sno) references Student(sno),
   foreign key (Cno) references Course(cno)
  );
4. When creating the SC data table, the error is reported as follows
ERROR 1215 (HY000): Cannot add foreign key constraint
  • Error interpretation: Cannot add foreign key constraints
  • The reason for the error: Because the SC data table depends on the Student and Course tables, but the character set encoding of the Student and Course tables is specified as utf8 (in order to insert tuple data containing Chinese), and the default character set encoding of the SC table is latin1, The data table engine enging does not match, so an error is reported.

Three, solve

1. When creating the SC data table, also specify the character set encoding as utf8
#创建选课表
CREATE TABLE SC
	(Sno CHAR(9)  not null ,
   Cno CHAR(4)  not null ,
   Grade SMALLINT,
   primary key (sno,cno),
   foreign key (Sno) references student(sno),
   foreign key (Cno) references Course(cno)
  )ENGINE=InnoDB DEFAULT CHARSET=utf8;

Four, other possible causes of ERROR 1215 (HY000) error report

  • The data type of a single attribute column of the data table is inconsistent, which will cause the error. At this time, you only need to modify the data type of a single attribute column to be consistent.
  • The database master and slave table character sets are different
    • The error reported in the above process description is caused by the inconsistent character set encoding method of the entire data table when the table is created; that is, the data types of related columns in multiple tables are inconsistent
    • MySQL view and modify the method of character set
  • Data table engine enging mismatch caused

reference:

1.MySQL : ERROR 1215 (HY000): Cannot add foreign key constraint

2.ERROR 1215 (HY000): Cannot add foreign key constraint

Guess you like

Origin blog.csdn.net/szw_yx/article/details/104695320