MySQL多个复合外键

时间:2013-06-24 23:18:02

标签: mysql database

我有两个表,活动和广告系列(是的,它适用于内部自定义CRM应用程序,有点):

create table `tb_activities` (
 `organization_id` integer(20) unsigned not null default '0',
 `activity_id` integer(20) unsigned not null auto_increment,
 primary key (`activity_id`)
) engine=innodb default charset=utf8 pack_keys=1 row_format=compact;

create table `tb_campaigns` (
 `organization_id` integer(20) unsigned not null default '0',
 `campaign_id` integer(20) unsigned not null auto_increment,
 primary key (`campaign_id`)
) engine=innodb default charset=utf8 pack_keys=1 row_format=compact;

在第三个多对多表之间,两个表都有外键。

drop table if exists `tb_campaigns_activities`;
create table `tb_campaigns_activities` (
 `organization_id` integer(20) unsigned not null default '0',
 `campaign_id` integer(20) unsigned not null default '0',
 `activity_id` integer(20) unsigned not null default '0',
 primary key (`organization_id`,`campaign_id`,`activity_id`),
 foreign key `rc_campaigns_activities_a` (`organization_id`,`campaign_id`)
  references `tb_campaigns` (`organization_id`,`campaign_id`)
   on update restrict on delete restrict,
 foreign key `rc_campaigns_activities_b` (`organization_id`,`activity_id`)
  references `tb_activities` (`organization_id`,`activity_id`)
   on update restrict on delete restrict,
 key `dc_campaigns_activities_a` (`organization_id`,`campaign_id`),
 key `dc_campaigns_activities_b` (`organization_id`,`activity_id`)
) engine=innodb default charset=utf8 pack_keys=1 row_format=compact;

但是当我尝试安装它时,我得到一个105 mysql错误。到目前为止,我已经研究过这个错误是关于坏的坏形式的外键,我唯一能让它工作的方法是删除dc_campaigns_activities_a和dc_campaigns_activities_b关系。所以数据库抱怨逻辑错误,但我疯了还是什么?对我来说,这是一个完美的外键情景;这两个键共享organization_id是唯一的事情。为什么这不正确?

1 个答案:

答案 0 :(得分:2)

您只能在引用的表上添加外键作为外键。 (organization_id,campaign_id)不是tb_campaigns上的关键字(与活动相同)。列类型也必须匹配,但确实如此。