0

我有两个表并尝试创建外键约束,但出现错误:

[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 驱动程序进行的。

任何帮助表示赞赏

4

1 回答 1

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)
于 2015-04-10T16:17:07.483 回答