0

I got two tables, first one with some peoples' data, and second with some codes. What I want to do is set FK to make DB to check if new person data contains a "code" from the list from the second table. Both tables got PK on codes column, but I still receive error.

ERROR 1215: Cannot add foreign key constraint

SQL Statement:

ALTER TABLE `MYBASE`.`first_table` 

ADD CONSTRAINT `fk_new_fkey`

  FOREIGN KEY (`code_indentyfication`)

  REFERENCES `MYBASE`.`second_table` (`codes`)

  ON DELETE NO ACTION

  ON UPDATE NO ACTION



ERROR: Error when running failback script. Details follow.



ERROR 1050: Table 'first_table' already exists

SQL Statement:

CREATE TABLE `first_table` (

  `id` int(11) NOT NULL AUTO_INCREMENT,

  `code_indentyfication` varchar(2) COLLATE utf8_polish_ci NOT NULL,

  `number_identyfication` varchar(45) COLLATE utf8_polish_ci NOT NULL,

  `name` varchar(45) COLLATE utf8_polish_ci DEFAULT NULL,

  `surname` varchar(45) COLLATE utf8_polish_ci DEFAULT NULL,

  `adress` varchar(45) COLLATE utf8_polish_ci DEFAULT NULL,



  PRIMARY KEY (`id`,`code_indentyfication`)

) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci 

Codes are varchar(2) and I would like to set FK without making any change in columns set. Any ideas? I am using MySQL server, and this code was generated by MySQL Workbench if that helps.

4

1 回答 1

0

试试看:

ALTER TABLE `MYBASE`.`first_table` 
ADD FOREIGN KEY (`code_indentyfication`)
  REFERENCES `MYBASE`.`second_table` (`codes`);
于 2013-11-02T21:48:49.067 回答