Error when adding FOREIGN KEY in already created table

Asked

Viewed 1,014 times

-2

I have a table that I need to change to have a foreign key

ALTER TABLE bancocliente.product ADD CONSTRAINT fk_fabPro FOREIGN KEY (cod_fab) REFERENCES bancocliente.fabrica (code);

I get the error message:

Erro SQL (1452): Cannot add or update a child row: a foreign key constraint fails (`bancocliente`.`#sql-2eb8_2`, CONSTRAINT `fk_fabPro` FOREIGN KEY (`cod_fab`) REFERENCES `fabrica` (`code`))

Code of table creation:

CREATE TABLE `produto` (
    `code` INT(11) NOT NULL AUTO_INCREMENT,
    `cod_fab` INT(11) NOT NULL DEFAULT '0',
    `nome` VARCHAR(50) NOT NULL,
    `preco` FLOAT NOT NULL,
    PRIMARY KEY (`code`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=1
;

and table manufactures

CREATE TABLE `fabrica` (
    `code` INT(11) NOT NULL AUTO_INCREMENT,
    `nome` VARCHAR(50) NOT NULL,
    PRIMARY KEY (`code`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=6
;

Error image: inserir a descrição da imagem aqui

1 answer

0


The solution developed together with the help of @Rovannlinhalis

Backup tables to be changed product manufactures

for

product fabrica_bk

Delete data from tables

product manufactures

run the sql command: ALTER TABLE bancocliente.product ADD CONSTRAINT fk_fabPro FOREIGN KEY (cod_fab) REFERENCES bancocliente.fabrica (code);

After these steps, I again populated the tables correctly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.