FK在创建表时导致崩溃

时间:2017-05-09 14:18:41

标签: mysql sql foreign-keys foreign-key-relationship

以下CREATE TABLE不起作用:

CREATE TABLE IF NOT EXISTS `transacciones`.`jos_trans_sector` (
  `id_sector` INT NOT NULL,
  `nombre` VARCHAR(45) NULL DEFAULT NULL,
  PRIMARY KEY (`id_sector`),
  CONSTRAINT `fk_sector_empresa_sector1`
    FOREIGN KEY (`id_sector`)
    REFERENCES `transacciones`.`jos_trans_empresa_sector` (`id_sector`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

我得到: Error Code: 1005. Can't create table 'transacciones.jos_trans_sector' (errno: 150)

如果我使用SHOW ENGINE INNODB STATUS;,我会得到以下输出:

------------------------
LATEST FOREIGN KEY ERROR
------------------------
170509 16:14:06 Error in foreign key constraint of table transacciones/jos_trans_sector:

    FOREIGN KEY (`id_sector`)
    REFERENCES `transacciones`.`jos_trans_empresa_sector` (`id_sector`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB:
Cannot find an index in the referenced table where the [...]

我查了一些帖子,他们在idFK之间讨论了不同的类型,但我对两者都有相同的看法(INT

有什么想法吗?

提前致谢。

1 个答案:

答案 0 :(得分:1)

这里的问题是transacciones.jos_trans_empresa_sector表缺少id_sector列的索引,因此无法创建外键。

尝试添加唯一索引:

ALTER TABLE transacciones.jos_trans_empresa_sector
ADD UNIQUE INDEX idx_id_sector (id_sector);

然后再次尝试创建表。