无法添加FK约束#1215

时间:2015-12-29 16:07:17

标签: mysql sql database

我看到有关此错误的多个问题,但我无法弄清楚这个问题我需要帮助。所以,我的表(显示错误)具有以下结构:

CREATE TABLE IF NOT EXISTS `services_providers` (
  `GUID_users` char(36) NOT NULL,
  `GUID_services` char(36) NOT NULL,
  `GUID` char(36) NOT NULL,
  `lastUpdated` varchar(36),
  PRIMARY KEY (`GUID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

我将PK设置为每条记录的GUID,FK设置为GUID_usersGUID_services
FK由此查询设置:

ALTER TABLE `services_providers`
ADD CONSTRAINT `services_providers_ibfk_1` FOREIGN KEY (`GUID_users`) REFERENCES `users` (`GUID`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `services_providers_ibfk_2` FOREIGN KEY (`GUID_services`) REFERENCES `services` (`GUID`) ON DELETE CASCADE ON UPDATE CASCADE;

用户 - 结构

CREATE TABLE IF NOT EXISTS `users` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`GUID` char(36) NOT NULL,
`first_name` varchar(256) DEFAULT NULL,
`last_name` varchar(512) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `id_roles` (`id_roles`)
) ENGINE=InnoDB AUTO_INCREMENT=85 DEFAULT CHARSET=utf8;

服务 - 结构

CREATE TABLE IF NOT EXISTS `services` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`GUID` char(36) NOT NULL,
`name` varchar(256) DEFAULT NULL,
`duration` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `id_service_categories` (`id_service_categories`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

现在当我执行上面提到的改变时,我得到:

  

1215 - 无法添加外键约束

我只想添加FK来自表usersservices的每条记录的GUID,并将PK作为字段GUID

为什么会这样?

1 个答案:

答案 0 :(得分:1)

您通常会将外键约束添加到另一个表的主键。主键是id,而不是GUID。我建议您将这些列用于services_providers

如果您坚持使用GUID,请将其声明为unique