当我尝试填充我的灯具时,我遇到了问题。我有2张桌子(客户和合作伙伴)。
CREATE TABLE `partner` (
`id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`client_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`),
UNIQUE KEY `client_id` (`client_id`),
CONSTRAINT `partner_ibfk_3` FOREIGN KEY (`client_id`) REFERENCES `client`
(`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
CREATE TABLE `client` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`partner_id` tinyint(3) unsigned DEFAULT NULL,
`partner_ref` varchar(7) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `partner_ref` (`partner_ref`,`partner_id`),
KEY `partner_id` (`partner_id`),
CONSTRAINT `client_ibfk_1` FOREIGN KEY (`partner_id`) REFERENCES `partner`
(`id`),
) ENGINE=InnoDB AUTO_INCREMENT=667305 DEFAULT CHARSET=utf8 PACK_KEYS=0;
当我运行我的灯具时,我遇到了这个问题:
ERROR 1215(HY000)第863行:无法添加外键约束
我认为这是因为当创建表'partner'时,表'client'不是这样,因此找不到外键。
但是,如果我改变并将“客户”放在“伙伴”之前,问题就是一样。
感谢您的帮助!
答案 0 :(得分:1)
我找到了解决方案:
我删除了'partner'创建中的约束,并在使用ALTER TABLE创建'client'后添加了这个约束:
CREATE TABLE `partner` (
`id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`client_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`),
UNIQUE KEY `client_id` (`client_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
CREATE TABLE `client` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`partner_id` tinyint(3) unsigned DEFAULT NULL,
`partner_ref` varchar(7) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `partner_ref` (`partner_ref`,`partner_id`),
KEY `partner_id` (`partner_id`),
CONSTRAINT `client_ibfk_1` FOREIGN KEY (`partner_id`) REFERENCES `partner`
(`id`),
) ENGINE=InnoDB AUTO_INCREMENT=667305 DEFAULT CHARSET=utf8 PACK_KEYS=0;
ALTER TABLE `partner`
ADD CONSTRAINT `partner_ibfk_3` FOREIGN KEY (`client_id`) REFERENCES
`client` (`id`);