Error Code: 1215. Cannot add foreign key constraint (foreign keys)(错误代码: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 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.无法添加外键约束(外键)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:错误代码:1215.无法添加外键约束(外键)


- 在SQL中,如何为每个组选择前2行 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- SQL 临时表问题 2022-01-01
- 更改自动增量起始编号? 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01