我有两个表并尝试创建外键约束,我收到一个错误:
[SQL] ALTER TABLE `defectstdreference`
ADD CONSTRAINT `Relationship72` FOREIGN KEY (`improve_notice_doc_id`, `defect_id`, `client_id`) REFERENCES `improvementnoticedefect` (`doc_id`, `defect_id`, `client_id`);
[Err] 1215 - Cannot add foreign key constraint
以下是我的表格:
CREATE TABLE `improvementnoticedefect` (
`defect_id` int(11) NOT NULL,
`doc_id` bigint(20) NOT NULL,
`client_id` bigint(20) NOT NULL,
`description` varchar(20000) NOT NULL,
PRIMARY KEY (`defect_id`,`doc_id`,`client_id`),
KEY `Relationship68` (`doc_id`,`client_id`),
CONSTRAINT `Relationship68` FOREIGN KEY (`doc_id`, `client_id`) REFERENCES `improvementnotice` (`doc_id`, `client_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
第二
CREATE TABLE `defectstdreference` (
`reference_id` bigint(20) NOT NULL AUTO_INCREMENT,
`std_doc_id` bigint(20) NOT NULL,
`improve_notice_doc_id` bigint(20) NOT NULL,
`defect_id` int(11) NOT NULL,
`paragraph` varchar(4000) NOT NULL,
`client_id` bigint(20) NOT NULL,
PRIMARY KEY (`reference_id`),
KEY `Relationship70` (`std_doc_id`),
CONSTRAINT `Relationship70` FOREIGN KEY (`std_doc_id`) REFERENCES `std` (`doc_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
添加外键的查询:
ALTER TABLE `defectstdreference`
ADD CONSTRAINT `Relationship72` FOREIGN KEY (`improve_notice_doc_id`, `defect_id`, `client_id`) REFERENCES `improvementnoticedefect` (`doc_id`, `defect_id`, `client_id`);
实际上这个查询是由SymmetricDS通过mysql jdbc驱动程序完成的。
感谢任何帮助
答案 0 :(得分:0)
我怀疑这可能是因为外键引用子句中的字段与主键的顺序不同。例如:
mysql> create table pk (id1 integer, id2 integer, id3 integer, primary key(id1, id2, id3));
Query OK, 0 rows affected (0.10 sec)
mysql> create table fk (id1 integer, id2 integer, id3 integer, foreign key(id1, id2, id3) references pk(id2, id1, id3));
ERROR 1005 (HY000): Can't create table 'test.fk' (errno: 150)
mysql> create table fk (id1 integer, id2 integer, id3 integer, foreign key(id1, id2, id3) references pk(id1, id2, id3));
Query OK, 0 rows affected (0.09 sec)