MySQL Error : #1005 - Can't create table (errno: 150) When I try create more than 1 FK

和自甴很熟 提交于 2019-12-07 01:33:59

问题


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 have created a fk sugestoes.idproduto -> produtos.id working, but I want each of the other fields also refer to the produtos.id through new FK. Run this command below that return MySQL Error : #1005 - Can't 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 have any idea what's going on?


回答1:


Try this,

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 can not specify

ON DELETE SET NULL

Because of this:

You have defined a SET NULL condition though some of the columns are defined as NOT NULL

You can see exact error when you run

SHOW ENGINE INNODB STATUS;



回答2:


Perhaps removing the 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 second thought, how do you expect the ON DELETE SET NULL to behave when your column is defined with NOT NULL ?


And third, does the table has any data in it? If some of the rows violate this FK constraint, then you can't create that FK.



来源:https://stackoverflow.com/questions/9937490/mysql-error-1005-cant-create-table-errno-150-when-i-try-create-more-tha

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!