复合主键对外键的影响

表结构1

      Table: t1
Create Table: CREATE TABLE `t1` (
  `a` int(11) NOT NULL DEFAULT '0',
  `b` int(11) NOT NULL DEFAULT '0',
  `c` int(11) NOT NULL DEFAULT '0',
  `name` varchar(20) DEFAULT NULL,
  `createtime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`a`,`b`,`c`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

表结构2

Table: t2
Create Table: CREATE TABLE `t2` (
  `id` int(11) NOT NULL,
  `d1` int(11) DEFAULT NULL,
  `d2` int(11) DEFAULT NULL,
  `d3` int(11) DEFAULT NULL,
  `name` varchar(20) DEFAULT NULL,
  `createtime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

constraint 外建名 foreign key(属性1.1,属性1.2,属性1.3,...,属性1.n) references t1(属性2.1,属性2.2,属性2.3,...属性2.n)

属性1和属性2的数目必须一致,并且属性2是来自于主表的主键字段,并且如果主表是复合主键则属性2字段的取值是有限制的

成功为t2设置外键的情况:

1.

alter table t2 add constraint fk foreign key(d1,d2,d3) references t1(a,b,c);

2.

alter table t2 add constraint fk foreign key(d1,d2) references t1(a,b);

3.

alter table t2 add constraint fk foreign key(d1) references t1(a);

foreign key(d1,d2,d3)中(d1,d2,d3)的顺序无所谓

references t1(a,b,c)必需按照a,b,c的顺序,必须先有a,才有b才有c

(b,c),(c),(a,c,b),(b,a,c)等都是错误的

原文地址:https://www.cnblogs.com/bibiafa/p/9233946.html