问题描述
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 ensure 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
列应该是学生表(虽然我相信 MySQL 允许这是一个唯一键,而不是主键,甚至只是在上面有一个索引.)
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.无法添加外键约束(外键)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!