无法在mysql

时间:2016-07-12 18:19:02

标签: mysql database composite-primary-key

我在mysql中的不同数据库上有两个表。我试图从一个表到另一个表创建一个复合外键,由于某种原因它不起作用。 仅当我使用单个主键字段而不是复合键时才有效。

以下示例中的问题约束是fk_dummy_table11。我在执行语句时得到Error Code: 1215. Cannot add foreign key constraint

为" dummy"创建表语句在DB NREAP中:

CREATE TABLE IF NOT EXISTS `NREAP`.`dummy` (
  `id` INT NOT NULL,
  `table1_TDO_COD_TIP_DOC` VARCHAR(14) NOT NULL,
  `table1_RFI_NUM_DOC` INT NOT NULL,
  `table1_RFI_VER_DOC` INT NOT NULL,
  `table1_RFI_NOM_FIC` VARCHAR(128) NOT NULL,
  PRIMARY KEY (`id`),
  INDEX `fk_dummy_table11_idx` (`table1_TDO_COD_TIP_DOC` ASC, `table1_RFI_NUM_DOC` ASC, `table1_RFI_VER_DOC` ASC, `table1_RFI_NOM_FIC` ASC),
  CONSTRAINT `fk_dummy_table11`
    FOREIGN KEY (`table1_TDO_COD_TIP_DOC` , `table1_RFI_NUM_DOC` , `table1_RFI_VER_DOC` , `table1_RFI_NOM_FIC`)
    REFERENCES `TRANS`.`table1` (`TDO_COD_TIP_DOC` , `RFI_NUM_DOC` , `RFI_VER_DOC` , `RFI_NOM_FIC`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

为" table1"创建表语句在DB TRANS:

CREATE TABLE IF NOT EXISTS `TRANS`.`table1` (
  `TDO_COD_TIP_DOC` VARCHAR(14) NOT NULL,
  `RFI_NUM_DOC` INT NOT NULL,
  `RFI_VER_DOC` INT NOT NULL,
  `RFI_NOM_FIC` VARCHAR(128) NOT NULL,
  `RFI_LOC_FIC` VARCHAR(1000) NULL,
  `RFI_DES_FIC` VARCHAR(255) NULL,
  `RFI_TIPO` VARCHAR(100) NOT NULL,
  `DAT_ALT` DATE NOT NULL,
  `COD_UTI_ALT` VARCHAR(14) NOT NULL,
  `DFI_VER_DOC` INT NULL,
  `DFI_NUM_SEQ` INT NULL,
  `CAM_ANO_INI_CAM` VARCHAR(4) NULL,
  PRIMARY KEY (`TDO_COD_TIP_DOC`, `RFI_NUM_DOC`, `RFI_VER_DOC`, `RFI_NOM_FIC`))
ENGINE = InnoDB;

请帮助,这太令人沮丧......

Edit1 - 我正在运行mysql版本5.7.12

Edit2 - 我已经运行了SHOW ENGINE INNODB STATUS命令,它给了我以下输出:

我正在运行mysql版本5.7.12,它是我认为的最新版本。

我跑过innodb状态:

------------------------
LATEST FOREIGN KEY ERROR
------------------------
2016-07-13 10:28:34 0x124c Error in foreign key constraint of table nreap/dummy:

        FOREIGN KEY (`table1_TDO_COD_TIP_DOC` , `table1_RFI_NUM_DOC` , `table1_RFI_VER_DOC` , `table1_RFI_NOM_FIC`)
        REFERENCES `TRANS`.`table1` (`TDO_COD_TIP_DOC` , `RFI_NUM_DOC` , `RFI_VER_DOC` , `RFI_NOM_FIC`)
        ON DELETE NO ACTION
        ON UPDATE NO ACTION)
    ENGINE = InnoDB:
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
Please refer to http://dev.mysql.com/doc/refman/5.7/en/innodb-foreign-key-constraints.html for correct foreign key definition.

1 个答案:

答案 0 :(得分:0)

我终于找到了问题所在。

我已经将其缩小到使用VARCHAR键的问题,限制与其他数据类型一起工作正常。经过几次实验后,我为每个模式添加了一个特定的字符集,并且它有效。在每个表中添加特定的字符集也可以。

感谢您的帮助!