我尝试使用此查询添加外键:
ALTER TABLE `StripeBilling`
ADD CONSTRAINT `StripeBillingPatientRef`
FOREIGN KEY (PatientRef)
REFERENCES `Patient`(`PatientId`)
ON DELETE SET NULL;
我的表mysql_dump是:
CREATE TABLE IF NOT EXISTS `StripeBilling` (
...
`PatientRef` int(10) unsigned DEFAULT NULL,
...
) ENGINE=InnoDB AUTO_INCREMENT=10000000 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
ALTER TABLE `StripeBilling`
ADD PRIMARY KEY (`StripeBillingId`), ADD KEY `StripeBillingAgentRef` (`AgentRef`), ADD KEY `PatientRef` (`PatientRef`);
ALTER TABLE `StripeBilling`
MODIFY `StripeBillingId` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=10000000;
ALTER TABLE `StripeBilling`
ADD CONSTRAINT `StripeBillingAgentRef` FOREIGN KEY (`AgentRef`) REFERENCES `Agent` (`AgentId`) ON DELETE SET NULL;
病人的表是:
CREATE TABLE IF NOT EXISTS `Patient` (
`PatientId` int(10) unsigned NOT NULL,
...
) ENGINE=InnoDB AUTO_INCREMENT=10000000 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
ALTER TABLE `Patient`
ADD PRIMARY KEY (`PatientId`), ADD UNIQUE KEY `PatientSerial` (`PatientSerial`);
ALTER TABLE `Patient`
MODIFY `PatientId` int(10) unsigned NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=10000000;
但MySQL返回错误:
无法添加或更新子行:外键约束失败 (
newportal_enc
。#sql-3863_9f
,CONSTRAINTStripeBillingPatientRef
FOREIGN KEY(PatientRef
)参考Patient
(PatientId
)ON DELETE SET NULL)
我感到困惑,因为我的数据库中不存在表newportal_enc.#sql-3863_9f
。
这不是由于PatientRef
索引的存在,因为删除此索引后我的问题仍然存在。
为什么我会收到此错误,如何解决?