无法为 mysql 中的不同数据库创建外键

Cannot create foreign key to different database in mysql

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

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

在数据库 NREAP 中为 "dummy" 创建 table 语句:

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;

在 DB TRANS:

中为 "table1" 创建 table 语句
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.

我终于找到了问题所在。

我已将其缩小为使用 VARCHAR 键时出现的问题,该限制适用于其他数据类型。经过几次实验后,我为每个模式添加了一个特定的字符集并且它起作用了。将特定字符集添加到每个 table 也有效。

感谢您的帮助!