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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)
SQL/MySQL: split a quantity value into multiple rows by date(SQL/MySQL:按日期将数量值拆分为多行)