错误代码:1215.无法添加外键约束(外键)

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Can#39;t Create Entity Data Model - using MySql and EF6(无法创建实体数据模型 - 使用 MySql 和 EF6)
MySQL select with CONCAT condition(MySQL选择与CONCAT条件)
Capitalize first letter of each word, in existing table(将现有表格中每个单词的首字母大写)
How to retrieve SQL result column value using column name in Python?(如何在 Python 中使用列名检索 SQL 结果列值?)
Update row with data from another row in the same table(使用同一表中另一行的数据更新行)
Exporting results of a Mysql query to excel?(将 Mysql 查询的结果导出到 excel?)