Search code examples
sqlmysqlforeign-keysconstraints

why can not add this foreign key?


I have this schema:

CREATE TABLE  `lotto`.`combinaciones` (
  `indice` mediumint(8) unsigned NOT NULL,
  `binario` int(10) unsigned NOT NULL,
  PRIMARY KEY  USING BTREE (`indice`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

CREATE TABLE  `lotto`.`sorteo` (
  `numeroSorteo` int(11) NOT NULL,
  `fechaSorteo` date NOT NULL,
  `precioCarton` double NOT NULL,
  `valorSerial` double NOT NULL,
  `valorMiniserial` double NOT NULL,
  `estatusSorteo` int(11) NOT NULL,
  `cantidadCartones` int(11) NOT NULL,
  PRIMARY KEY  (`numeroSorteo`),
  UNIQUE KEY `fechaSorteo` (`fechaSorteo`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

CREATE TABLE  `lotto`.`cartones` (
  `numeroSorteo` int(11) NOT NULL,
  `serial` mediumint(9) NOT NULL,
  `indice` mediumint(8) NOT NULL,
  `binario` int(11) NOT NULL,
  `miniserial` smallint(6) NOT NULL,
  `estatus` tinyint(4) NOT NULL default '0',
  PRIMARY KEY  (`numeroSorteo`,`serial`),
  KEY `new_index` (`indice`), -- ADD LATER
  CONSTRAINT `cartones_ibfk_1` FOREIGN KEY (`numeroSorteo`) REFERENCES `sorteo` (`numeroSorteo`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

I'm trying to add this:

ALTER TABLE `lotto`.`cartones` ADD CONSTRAINT `new_fk_56` FOREIGN KEY `new_fk_56` (`indice`)
    REFERENCES `combinaciones` (`indice`)
    ON DELETE RESTRICT
    ON UPDATE RESTRICT;

BUT INNODB keeps complain about not finding an indice:

Cannot find an index in the referenced table where the referenced columns appear as the first columns...

But it's not the foreign key: combinaciones(indice) the same as the foreign key sorteo(numeroSorteo)?, which is working

EDIT:

I've tested with: KEY 'new_index' (indice) in lotto.cartones and without it.


Solution

  • `indice` mediumint(8) NOT NULL,
    

    is not the same type as

    `indice` mediumint(8) unsigned NOT NULL,
    

    You need to make both of your indice unsigned or neither of them unsigned.