“外键约束不正确”

时间:2014-09-25 11:20:28

标签: mysql sql mysql-workbench mariadb

我有这个SQL代码:

CREATE TABLE IF NOT EXISTS `deputy`.`Votings` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `VRSetId` INT UNSIGNED NOT NULL,
  `LNSetIdOfMeeting` INT UNSIGNED NOT NULL,
  `VRSetIdOfMeeting` INT UNSIGNED NOT NULL,
  `meetingId` INT UNSIGNED NOT NULL,
  PRIMARY KEY (`id`, `VRSetId`),
  CONSTRAINT `fk_Votings_VotingRulesSets1`
    FOREIGN KEY (`VRSetId`)
    REFERENCES `deputy`.`VRSets` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_Votings_Meetings1`
    FOREIGN KEY (`LNSetIdOfMeeting` , `VRSetIdOfMeeting` , `meetingId`)
    REFERENCES `deputy`.`Meetings` (`LNSetId` , `VRSetId` , `id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

主键由两个字段组成:" id"和" VRSetId&#34 ;; " VRSetId"也是外键,因为有" VRSets"与'"投票"确定一对一关系的表格。还有第二个外键,会议"会议"除了" id"之外,表本身还有两个外键创建的主键。领域......"会议" table与" Votings"有一对多的关系。所以"投票"最终得到了这么多钥匙......这很好,因为我用它们以很多不同的方式获取我的数据。问题在于,因为我已经为所有" id"添加了自动递增功能。字段 - 我收到了这样的错误:

ERROR: Error 1005: Can't create table `deputy`.`Votings` (errno: 150 "Foreign key constraint is incorrectly formed")

有这个"会议"具有类似格式的密钥的表格,它工作正常:

CREATE TABLE IF NOT EXISTS `deputy`.`Meetings` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `LNSetId` INT UNSIGNED NOT NULL,
  `VRSetId` INT UNSIGNED NOT NULL,
  `LNSetIdOfCSet` INT UNSIGNED NOT NULL,
  `CSetId` INT UNSIGNED NOT NULL,
  PRIMARY KEY (`id`, `LNSetId`, `VRSetId`),
  CONSTRAINT `fk_Meetings_LegalNumbersSets1`
    FOREIGN KEY (`LNSetId`)
    REFERENCES `deputy`.`LNSets` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_Meetings_VotingRulesSets1`
    FOREIGN KEY (`VRSetId`)
    REFERENCES `deputy`.`VRSets` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_Meetings_ConfigurationSets1`
    FOREIGN KEY (`LNSetIdOfCSet` , `CSetId`)
    REFERENCES `deputy`.`CSets` (`LNSetId` , `id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

最后一张表与" Votings" (我已删除所有表格中的数据字段,使其看起来更清晰):

CREATE TABLE IF NOT EXISTS `deputy`.`VRSets` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`))
ENGINE = InnoDB;

数据库在我做了一些小改动之前工作正常,现在我不知道发生了什么......整个事情是由MySQL Workbench自动生成的,我是&#39 ; m将脚本运行到MariaDB上。

1 个答案:

答案 0 :(得分:3)

引用的列需要索引。您meetings表上的主键是

PRIMARY KEY (`id`, `LNSetId`, `VRSetId`)

但是您在votings表格中引用了这样的内容:

FOREIGN KEY (`LNSetIdOfMeeting` , `VRSetIdOfMeeting` , `meetingId`)
REFERENCES `deputy`.`Meetings` (`LNSetId` , `VRSetId` , `id`)

索引中列的顺序很重要,因此将其更改为

FOREIGN KEY (`meetingId`, `LNSetIdOfMeeting` , `VRSetIdOfMeeting`)
REFERENCES `deputy`.`Meetings` (`id`, `LNSetId` , `VRSetId`)

它会起作用。