MySQL无法添加外键约束

阳光穿透心脏的1/2处 2022-11-28 13:54 209阅读 0赞

本文翻译自:MySQL Cannot Add Foreign Key Constraint

So I’m trying to add Foreign Key constraints to my database as a project requirement and it worked the first time or two on different tables, but I have two tables on which I get an error when trying to add the Foreign Key Constraints. 因此,作为项目需求,我试图将外键约束添加到数据库中,并且它第一次或在两个不同的表上运行,但是在尝试添加外键约束时,我在两个表上遇到了错误。 The error message that I get is: 我收到的错误消息是:

ERROR 1215 (HY000): Cannot add foreign key constraint 错误1215(HY000):无法添加外键约束

This is the SQL I’m using to create the tables, the two offending tables are Patient and Appointment . 这是我用来创建表的SQL,两个有问题的表是PatientAppointment

  1. SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
  2. SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=1;
  3. SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
  4. CREATE SCHEMA IF NOT EXISTS `doctorsoffice` DEFAULT CHARACTER SET utf8 ;
  5. USE `doctorsoffice` ;
  6. -- -----------------------------------------------------
  7. -- Table `doctorsoffice`.`doctor`
  8. -- -----------------------------------------------------
  9. DROP TABLE IF EXISTS `doctorsoffice`.`doctor` ;
  10. CREATE TABLE IF NOT EXISTS `doctorsoffice`.`doctor` (
  11. `DoctorID` INT(11) NOT NULL AUTO_INCREMENT ,
  12. `FName` VARCHAR(20) NULL DEFAULT NULL ,
  13. `LName` VARCHAR(20) NULL DEFAULT NULL ,
  14. `Gender` VARCHAR(1) NULL DEFAULT NULL ,
  15. `Specialty` VARCHAR(40) NOT NULL DEFAULT 'General Practitioner' ,
  16. UNIQUE INDEX `DoctorID` (`DoctorID` ASC) ,
  17. PRIMARY KEY (`DoctorID`) )
  18. ENGINE = InnoDB
  19. DEFAULT CHARACTER SET = utf8;
  20. -- -----------------------------------------------------
  21. -- Table `doctorsoffice`.`medicalhistory`
  22. -- -----------------------------------------------------
  23. DROP TABLE IF EXISTS `doctorsoffice`.`medicalhistory` ;
  24. CREATE TABLE IF NOT EXISTS `doctorsoffice`.`medicalhistory` (
  25. `MedicalHistoryID` INT(11) NOT NULL AUTO_INCREMENT ,
  26. `Allergies` TEXT NULL DEFAULT NULL ,
  27. `Medications` TEXT NULL DEFAULT NULL ,
  28. `ExistingConditions` TEXT NULL DEFAULT NULL ,
  29. `Misc` TEXT NULL DEFAULT NULL ,
  30. UNIQUE INDEX `MedicalHistoryID` (`MedicalHistoryID` ASC) ,
  31. PRIMARY KEY (`MedicalHistoryID`) )
  32. ENGINE = InnoDB
  33. DEFAULT CHARACTER SET = utf8;
  34. -- -----------------------------------------------------
  35. -- Table `doctorsoffice`.`Patient`
  36. -- -----------------------------------------------------
  37. DROP TABLE IF EXISTS `doctorsoffice`.`Patient` ;
  38. CREATE TABLE IF NOT EXISTS `doctorsoffice`.`Patient` (
  39. `PatientID` INT unsigned NOT NULL AUTO_INCREMENT ,
  40. `FName` VARCHAR(30) NULL ,
  41. `LName` VARCHAR(45) NULL ,
  42. `Gender` CHAR NULL ,
  43. `DOB` DATE NULL ,
  44. `SSN` DOUBLE NULL ,
  45. `MedicalHistory` smallint(5) unsigned NOT NULL,
  46. `PrimaryPhysician` smallint(5) unsigned NOT NULL,
  47. PRIMARY KEY (`PatientID`) ,
  48. UNIQUE INDEX `PatientID_UNIQUE` (`PatientID` ASC) ,
  49. CONSTRAINT `FK_MedicalHistory`
  50. FOREIGN KEY (`MEdicalHistory` )
  51. REFERENCES `doctorsoffice`.`medicalhistory` (`MedicalHistoryID` )
  52. ON DELETE CASCADE
  53. ON UPDATE CASCADE,
  54. CONSTRAINT `FK_PrimaryPhysician`
  55. FOREIGN KEY (`PrimaryPhysician` )
  56. REFERENCES `doctorsoffice`.`doctor` (`DoctorID` )
  57. ON DELETE CASCADE
  58. ON UPDATE CASCADE)
  59. ENGINE = InnoDB;
  60. -- -----------------------------------------------------
  61. -- Table `doctorsoffice`.`Appointment`
  62. -- -----------------------------------------------------
  63. DROP TABLE IF EXISTS `doctorsoffice`.`Appointment` ;
  64. CREATE TABLE IF NOT EXISTS `doctorsoffice`.`Appointment` (
  65. `AppointmentID` smallint(5) unsigned NOT NULL AUTO_INCREMENT ,
  66. `Date` DATE NULL ,
  67. `Time` TIME NULL ,
  68. `Patient` smallint(5) unsigned NOT NULL,
  69. `Doctor` smallint(5) unsigned NOT NULL,
  70. PRIMARY KEY (`AppointmentID`) ,
  71. UNIQUE INDEX `AppointmentID_UNIQUE` (`AppointmentID` ASC) ,
  72. CONSTRAINT `FK_Patient`
  73. FOREIGN KEY (`Patient` )
  74. REFERENCES `doctorsoffice`.`Patient` (`PatientID` )
  75. ON DELETE CASCADE
  76. ON UPDATE CASCADE,
  77. CONSTRAINT `FK_Doctor`
  78. FOREIGN KEY (`Doctor` )
  79. REFERENCES `doctorsoffice`.`doctor` (`DoctorID` )
  80. ON DELETE CASCADE
  81. ON UPDATE CASCADE)
  82. ENGINE = InnoDB;
  83. -- -----------------------------------------------------
  84. -- Table `doctorsoffice`.`InsuranceCompany`
  85. -- -----------------------------------------------------
  86. DROP TABLE IF EXISTS `doctorsoffice`.`InsuranceCompany` ;
  87. CREATE TABLE IF NOT EXISTS `doctorsoffice`.`InsuranceCompany` (
  88. `InsuranceID` smallint(5) NOT NULL AUTO_INCREMENT ,
  89. `Name` VARCHAR(50) NULL ,
  90. `Phone` DOUBLE NULL ,
  91. PRIMARY KEY (`InsuranceID`) ,
  92. UNIQUE INDEX `InsuranceID_UNIQUE` (`InsuranceID` ASC) )
  93. ENGINE = InnoDB;
  94. -- -----------------------------------------------------
  95. -- Table `doctorsoffice`.`PatientInsurance`
  96. -- -----------------------------------------------------
  97. DROP TABLE IF EXISTS `doctorsoffice`.`PatientInsurance` ;
  98. CREATE TABLE IF NOT EXISTS `doctorsoffice`.`PatientInsurance` (
  99. `PolicyHolder` smallint(5) NOT NULL ,
  100. `InsuranceCompany` smallint(5) NOT NULL ,
  101. `CoPay` INT NOT NULL DEFAULT 5 ,
  102. `PolicyNumber` smallint(5) NOT NULL AUTO_INCREMENT ,
  103. PRIMARY KEY (`PolicyNumber`) ,
  104. UNIQUE INDEX `PolicyNumber_UNIQUE` (`PolicyNumber` ASC) ,
  105. CONSTRAINT `FK_PolicyHolder`
  106. FOREIGN KEY (`PolicyHolder` )
  107. REFERENCES `doctorsoffice`.`Patient` (`PatientID` )
  108. ON DELETE CASCADE
  109. ON UPDATE CASCADE,
  110. CONSTRAINT `FK_InsuranceCompany`
  111. FOREIGN KEY (`InsuranceCompany` )
  112. REFERENCES `doctorsoffice`.`InsuranceCompany` (`InsuranceID` )
  113. ON DELETE CASCADE
  114. ON UPDATE CASCADE)
  115. ENGINE = InnoDB;
  116. USE `doctorsoffice` ;
  117. SET SQL_MODE=@OLD_SQL_MODE;
  118. SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
  119. SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;

#1楼

参考:https://stackoom.com/question/13bm9/MySQL无法添加外键约束


#2楼

To find the specific error run this: 要查找特定错误,请运行以下命令:

  1. SHOW ENGINE INNODB STATUS;

And look in the LATEST FOREIGN KEY ERROR section. 并查看“ LATEST FOREIGN KEY ERROR部分。

The data type for the child column must match the parent column exactly. 子列的数据类型必须与父列完全匹配。 For example, since medicalhistory.MedicalHistoryID is an INT , Patient.MedicalHistory also needs to be an INT , not a SMALLINT . 例如,由于medicalhistory.MedicalHistoryIDINTPatient.MedicalHistory也需要一个INT ,而不是一个SMALLINT

Also, you should run the query set foreign_key_checks=0 before running the DDL so you can create the tables in an arbitrary order rather than needing to create all parent tables before the relevant child tables. 另外,您应该在运行DDL之前运行查询set foreign_key_checks=0 ,以便可以以任意顺序创建表,而不需要在相关子表之前创建所有父表。


#3楼

Try to use the same type of your primary keys - int(11) - on the foreign keys - smallint(5) - as well. 尝试在外键-smallint(5)上使用相同类型的主键-int(11) -。

Hope it helps! 希望能帮助到你!


#4楼

Check following rules : 检查以下规则:

  • First checks whether names are given right for table names 首先检查表名是否正确命名
  • Second right data type give to foreign key ? 次权数据类型赋予外键?

#5楼

I had a similar error in creating foreign key in a Many to Many table where the primary key consisted of 2 foreign keys and another normal column. 在“多对多”表中创建外键时,我遇到了类似的错误,该表的主键由2个外键和另一个普通列组成。 I fixed the issue by correcting the referenced table name ie company, as shown in the corrected code below: 我通过更正引用的表名即company来解决此问题,如下面的更正代码所示:

  1. create table company_life_cycle__history -- (M-M)
  2. (
  3. company_life_cycle_id tinyint unsigned not null,
  4. Foreign Key (company_life_cycle_id) references company_life_cycle(id) ON DELETE CASCADE ON UPDATE CASCADE,
  5. company_id MEDIUMINT unsigned not null,
  6. Foreign Key (company_id) references company(id) ON DELETE CASCADE ON UPDATE CASCADE,
  7. activity_on date NOT NULL,
  8. PRIMARY KEY pk_company_life_cycle_history (company_life_cycle_id, company_id,activity_on),
  9. created_on datetime DEFAULT NULL,
  10. updated_on datetime DEFAULT NULL,
  11. created_by varchar(50) DEFAULT NULL,
  12. updated_by varchar(50) DEFAULT NULL
  13. );

#6楼

To set a FOREIGN KEY in Table B you must set a KEY in the table A. 要在表B中设置外键,必须在表A中设置键。

In table A: INDEX id ( id ) 在表A中:INDEX idid

And then in the table B, 然后在表B中,

  1. CONSTRAINT `FK_id` FOREIGN KEY (`id`) REFERENCES `table-A` (`id`)

发表评论

表情:
评论列表 (有 0 条评论,209人围观)

还没有评论,来说两句吧...

相关阅读

    相关 MySQL约束

    MySQL外键约束 外键约束(FOREIGN KRY,缩写FK)是用来实现数据库表的参照完整性约束的。 外键约束可以是两张表紧密的结合起来,特别是针对修改或者删除的级联

    相关 mysql约束

    1.外键 如果公共关键字在一个关系中是主关键字,那么这个公共关键字被称为另一个关系的外键。就是A表的主键,被用到了B表中,此时它就成了外键 ![在这里插入图片描述][

    相关 MySQL约束

    关系键是关系数据库的重要组成部分。关系键是一个表中的一个或几个属性,用来标识该表的每一行或与另一个表产生联系。 其中就包括外键 1 主键(primary key或uniqu

    相关 Mysql约束

            Mysql集群创建外键,分为四种约束:no action,restrict,cascade,set null。如果表A的主关键字是表B中的字段,则该字段称为B的

    相关 MySQL&约束

    今天给大家分享一下关于MySQL外键的知识内容 如果表A的主关键字是表B中的字段,则该字段称为表B的外键,表A称为主表,表B称为从表。外键是用来实现参照完整性的,

    相关 Mysql添加约束.

    CASCADE 删除:删除主表时自动删除从表。删除从表,主表不变 更新:更新主表时自动更新从表。更新从表,主表不变 SET NULL 删除:删除主表时自动更...