无法创建约束键

时间:2018-07-20 09:21:35

标签: mysql database foreign-keys constraints creation

我有以下3个MySQL表:

应用程序:

CREATE TABLE IF NOT EXISTS `apps` (
    `identifier` INT NOT NULL AUTO_INCREMENT,
    `id` VARCHAR(255) NOT NULL,
    `name` VARCHAR(255) NULL,
    `description` VARCHAR(255) NULL,
    `cloud` VARCHAR(255) NULL,
    `onpremise` VARCHAR(255) NULL,
    `type` VARCHAR(255) NULL,
    `editor` VARCHAR(255) NULL,
    `provider` VARCHAR(255) NULL,
    `administrators` INT NULL,
    PRIMARY KEY(`identifier`),

    CONSTRAINT admin_ref_team
    FOREIGN KEY(`administrators`) REFERENCES `teams`(`identifier`)
    ON DELETE CASCADE
    ON UPDATE CASCADE
);

质量:

CREATE TABLE IF NOT EXISTS `quality` (
    `identifier` INT NOT NULL AUTO_INCREMENT,
    `quality` VARCHAR(255) NOT NULL,
    `label` VARCHAR(255) NOT NULL,
    PRIMARY KEY(`identifier`)
);

应用和质量的关联:

CREATE TABLE IF NOT EXISTS `assoc_apps_quality` (
    `identifier` INT NOT NULL AUTO_INCREMENT,
    `apps_id` VARCHAR(255) NOT NULL,
    `quality_id` INT NOT NULL,

    PRIMARY KEY(`identifier`),
    CONSTRAINT apps_ref_quality
    FOREIGN KEY(`apps_id`) REFERENCES `apps`(`identifier`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,

    CONSTRAINT quality_ref_apps
    FOREIGN KEY(`quality_id`) REFERENCES `quality`(`identifier`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION
);

Apps and Quality已创建,但是第三张表却给了我这个错误,我无法创建它:

Error in query (1215): Cannot add foreign key constraint

我看不出问题出在哪里。约束名称在所有数据库中都是唯一的,没有拼写错误。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

您在“ quality_ref_apps”中定义的apps_id错误,请在sql下面尝试。

CREATE TABLE IF NOT EXISTS `assoc_apps_quality` (
`identifier` INT NOT NULL AUTO_INCREMENT,
`apps_id` INT NOT NULL,
`quality_id` INT NOT NULL,

PRIMARY KEY(`identifier`),
CONSTRAINT apps_ref_quality
FOREIGN KEY(`apps_id`) REFERENCES `apps`(`identifier`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,

CONSTRAINT quality_ref_apps
FOREIGN KEY(`quality_id`) REFERENCES `quality`(`identifier`)
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
  

apps_id VARCHAR(255) NOT NULL,更改为apps_id INT NOT NULL,

答案 1 :(得分:1)

检查数据类型。

   FOREIGN KEY(`apps_id`) REFERENCES `apps`(`identifier`)

apps_id为VARCHAR,

标识符为INT