復合主鍵對外鍵的影響


表結構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)等都是錯誤的

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM