MySQL Error: # 1005 - Cannot create table (errno: 150) When I try to create more than 1 FK

I have this table:

CREATE TABLE IF NOT EXISTS `produtos` ( `id` int(11) NOT NULL auto_increment, `idcatprodutos` int(11) NOT NULL, `idcategoria` int(11) NOT NULL, `idmarca` int(11) NOT NULL, `nome` varchar(100) NOT NULL, PRIMARY KEY (`id`), KEY `FK_produtos_2` (`idcatprodutos`), KEY `FK_produtos_3` (`idmarca`), KEY `FK_produtos_4` (`idcategoria`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=DYNAMIC AUTO_INCREMENT=39 ; 

and this table:

 CREATE TABLE IF NOT EXISTS `sugestoes` ( `id` int(11) NOT NULL auto_increment, `idproduto` int(11) NOT NULL, `idsugestao1` int(11) NOT NULL, `idsugestao2` int(11) NOT NULL, `idsugestao3` int(11) NOT NULL, `idsugestao4` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `FK_sugestoes_prod` (`idproduto`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=FIXED AUTO_INCREMENT=9 ; 

I already created fk sugestoes.idproduto -> produtos.id , but I want each of the other fields to also produtos.id to the new FK. Run the following command that returns a MySQL error: # 1005 - Unable to create table (errno: 150):

 ALTER TABLE `infantile`.`sugestoes` ADD CONSTRAINT `FK_sugestoes_2` FOREIGN KEY `FK_sugestoes_2` (`idsugestao1`) REFERENCES `produtos` (`id`) ON DELETE SET NULL ON UPDATE CASCADE , ROW_FORMAT = FIXED; 

Does anyone know what is going on?

+7
source share
2 answers

Try it,

it works:

 ALTER TABLE `sugestoes` ADD CONSTRAINT `FK_idproduto_produtos_1` FOREIGN KEY (`idproduto`) REFERENCES `produtos` (`id`), ADD CONSTRAINT `FK_sugestoes_produtos_2` FOREIGN KEY (`idsugestao1`) REFERENCES `produtos` (`id`), ADD CONSTRAINT `FK_sugestoes_produtos_3` FOREIGN KEY (`idsugestao2`) REFERENCES `produtos` (`id`), ADD CONSTRAINT `FK_sugestoes_produtos_4` FOREIGN KEY (`idsugestao3`) REFERENCES `produtos` (`id`), ADD CONSTRAINT `FK_sugestoes_produtos_5` FOREIGN KEY (`idsugestao4`) REFERENCES `produtos` (`id`) 

UPDATE:

You cannot specify

 ON DELETE SET NULL 

Because of this:

You defined a SET NULL condition, although some of the columns are defined as NOT NULL

You can see the exact error at startup

 SHOW ENGINE INNODB STATUS; 
+10
source

Possible removal of ROW_FORMAT = FIXED :

 ALTER TABLE `infantile`.`sugestoes` ADD CONSTRAINT `FK_sugestoes_2` FOREIGN KEY `FK_sugestoes_2` (`idsugestao1`) REFERENCES `produtos` (`id`) ON DELETE SET NULL ON UPDATE CASCADE ; 

On the other hand, how do you expect ON DELETE SET NULL to behave when your column is defined using NOT NULL ?


And thirdly, is there any data in the table? If some of the lines violate this FK constraint, you cannot create this FK.

0
source

All Articles