MySQL使用外键创建架构给出了错误1215

时间:2018-03-23 13:48:46

标签: mysql foreign-keys mysql-workbench

我在MySQL中创建了3个表的基本模式,其中一个有两个外键(documentreference表):

>>> from collections import namedtuple
>>> obj = namedtuple("Myobj", ["month", "temperature"])
>>> month_temperature  = list(map(lambda x: obj(*x), zip(month, temperature)))
>>> month_temperature[0].month
'Jan'
>>> month_temperature[0].temperature
34

但是在运行时出现以下错误:

-- Dumping database structure
CREATE DATABASE IF NOT EXISTS `zeus`;
USE `zeus`;

-- ****** FHIR RESOURCES ******
CREATE TABLE IF NOT EXISTS `patients` (
  `Id` int(5) NOT NULL AUTO_INCREMENT,
  `Active` bool,
  `Name` JSON, -- JSON blob array of HumanName DataTypes
  `Telecom` JSON, -- JSON blob array of ContactPoint DataTypes
  `Gender` varchar(10),
  `BirthDate` datetime,
  `DeceasedBoolean` bool,
  `DeceasedDateTime` datetime,
  `Address` JSON, -- JSON array of Address DataTypes
  `MaritalStatus` JSON, -- JSON blob single CodeableConcept DataType
  `MultipleBirthBoolean` bool,
  `MultipleBirthInteger` int(5),
  `Communication` JSON, -- JSON array of languages & preferred bool i.e "[language: CodeableConcept(English), preffered: true, ...]"
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=latin1;


CREATE TABLE IF NOT EXISTS `documentreferences` (
  `Id` int(5) NOT NULL AUTO_INCREMENT,
  `Status` varchar(50),
  `DocStatus` varchar(50),
  `Type` JSON, -- single CodeableConcept DataType
  `Class` JSON, -- single CodeableConcept DataType
  `Created` datetime,
  `Indexed` datetime, 
  `Description` varchar(50),
  `SecurityLabel` JSON, -- array of CodeableConcept DataTypes
  `ContextEvent` JSON, -- array of CodeableConcept DataTypes
  `ContextPeriodStart` datetime,
  `ContextPeriodEnd` datetime,
  `ContextFacilityType` JSON, -- single CodeableConcept DataType
  `ContextPracticeSetting` JSON, -- single CodeableConcept DataType
  PRIMARY KEY (`id`),
  `SubjectId` int(5),
    INDEX subject_ind (SubjectId),
    FOREIGN KEY (SubjectId)
    REFERENCES patients(Id)
    ON DELETE CASCADE,
    -- ** FK below causes issue **
  `PractitionerId` int(5),
    INDEX practitioner_ind (PractitionerId),
    FOREIGN KEY (PractitionerId)
    REFERENCES practitioners(Id)
    ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS `practitioners` (
  `Id` int(5) NOT NULL AUTO_INCREMENT,
  `Active` bool,
  `Name` JSON, -- JSON blob array of HumanName DataTypes
  `Telecom` JSON, -- JSON array of ContactPoint DataTypes
  `Address` JSON, -- JSON array of Address DataTypes
  `Gender` varchar(10),
  `BirthDate` datetime,
  `Qualification` JSON,
  `Communication` JSON, -- JSON array of CodeableConcept DataTypes
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=latin1;

在从业者表上删除FK时,架构会运行。我当前的架构会导致错误有什么问题?任何见解都表示赞赏!

1 个答案:

答案 0 :(得分:1)

SQL喜欢把事情整理好。在将它们与外键关系链接之前,您需要声明所有表。只需将从业者表创建移到documentreferences表的上方,它就可以工作。