Search code examples
mysqljdbcsymmetricds

Foreign key error on MySQL


I have two tables and try to create foreign key constraint, and I get an error:

[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

Here are my tables:

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;

Second:

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;

And the query to add foreign keys:

ALTER TABLE `defectstdreference`
ADD CONSTRAINT `Relationship72` FOREIGN KEY (`improve_notice_doc_id`, `defect_id`, `client_id`) REFERENCES `improvementnoticedefect` (`doc_id`, `defect_id`, `client_id`);

Actually this query is made by SymmetricDS via mysql jdbc driver.

Any help is appreciated


Solution

  • I suspect it may be because the fields in your foreign key references clause are ordered differently to the primary key. example:

    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)