本文介绍了错误代码:1215.无法添加外键约束(外键)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

CREATE DATABASE my_db;

CREATE TABLE class (classID int NOT NULL AUTO_INCREMENT,
nameClass varchar(255),
classLeader varchar(255),
FOREIGN KEY (classLeader) REFERENCES student(studentID),
PRIMARY KEY (classID));

CREATE TABLE student (studentID int NOT NULL AUTO_INCREMENT,
lastName varchar(255),
firstName varchar(255),
classID int,
FOREIGN KEY (classID) REFERENCES class(classID),
PRIMARY KEY (studentID));

我试图通过使用外键保证表之间的数据一致性,以便DBMS可以检查错误;然而,似乎我们不能由于某种原因这样做。什么是错误,是否有一个替代?另外,当我填充一个有外键的表时,我不能填充为外键保留的字段,对吧?另外,是一个外键被认为是一个钥匙吗?

I am trying to insure data consistency between the tables by using foreign key so that the DBMS can check for errors; however, it seems we can't do that for some reason. What's the error and is there an alternative? Also, when I fill a table that has a foreign key, I can't fill the field that's reserved for the foreign key(s), right? Also, is a foreign key considered to be a key at all?

推荐答案

最有可能的问题是这一行:

The most likely issue is this line:

FOREIGN KEY (classLeader) REFERENCES student(studentID),

classLeader是VARCHAR(255)。必须匹配引用列... student.studentID 的数据类型。当然, student 表必须存在,并且 studentID 列必须存在,并且 studentID 列应该是学生表的PRIMARY KEY(虽然我相信MySQL允许这是一个UNIQUE KEY,而不是一个PRIMARY KEY,或者只是有一个索引)。

The datatype of classLeader is VARCHAR(255). That has to match the datatype of the referenced column... student.studentID. And of course, the student table has to exist, and the studentID column has to exist, and the studentID column should be the PRIMARY KEY of the student table (although I believe MySQL allows this to be a UNIQUE KEY, rather than a PRIMARY KEY, or even just have an index on it.)

在任何情况下,这里缺少的是 SHOW CREATE TABLE student;

In any case, what's missing here is the output from SHOW CREATE TABLE student;

数据类型不匹配。

classLeader VARCHAR 255)列不能是 studentID INT 的外键引用。

The classLeader VARCHAR(255) column cannot be a foreign key reference to studentID INT.

数据类型的两列必须匹配。

The datatypes of the two columns has to match.

这篇关于错误代码:1215.无法添加外键约束(外键)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 12:20