为什么不能添加这个外键?

时间:2009-09-27 07:57:40

标签: sql mysql foreign-keys constraints

我有这个架构:

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

我正在尝试添加此内容:

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

但是INNODB一直抱怨找不到指示:

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

但它不是外键:combinaciones(indice)和外键sorteo(numeroSorteo)相同?,哪个正在工作

编辑:

我已在KEY 'new_index' (中使用) indice lotto.cartones进行测试,但没有。{/ p>

1 个答案:

答案 0 :(得分:5)

`indice` mediumint(8) NOT NULL,

的类型不同
`indice` mediumint(8) unsigned NOT NULL,

您需要同时使indice无符号或两者都未签名。