MySql查询错误150谜题

时间:2017-08-14 03:01:02

标签: mysql errno mysql-error-1005

我必须为类项目创建和使用数据库。我使用mysql workbench在本地开发了数据库和应用程序。它需要托管在另一个名为myphpmyadmin的服务上。问题是当我使用该服务中的mysql执行行创建表时,我收到以下错误。

 Error
SQL query:

CREATE TABLE IF NOT EXISTS  `artists_residence` (

 `artists_id` INT( 11 ) ,
 `city_id` INT( 11 ) ,
PRIMARY KEY (  `artists_id` ,  `city_id` ) ,
CONSTRAINT FOREIGN KEY (  `artists_id` ) REFERENCES  `artists` (  `id` ) ON DELETE CASCADE ON UPDATE CASCADE ,
CONSTRAINT FOREIGN KEY (  `city_id` ) REFERENCES  `city` (  `id` ) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE = INNODB CHARSET = Latin1;

MySQL said: Documentation

#1005 - Can't create table 'fondellb-db.artists_residence' (errno: 150) 

这是mySql的整个文件,我试图执行。

CREATE TABLE IF NOT EXISTS `artists` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `fname` VARCHAR(255) NOT NULL,
  `lname` VARCHAR(255) NOT NULL,
  `year_of_birth` DATE NOT NULL,
  `year_of_death` DATE NULL DEFAULT NULL,
  PRIMARY KEY (`id`))
ENGINE = InnoDB CHARSET = Latin1;


CREATE TABLE IF NOT EXISTS `country` (
  `country_id` INT(11) NOT NULL,
  `name` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`country_id`))
ENGINE = InnoDB CHARSET = Latin1;


CREATE TABLE IF NOT EXISTS `city` (
  `id` INT(11) NOT NULL,
  `name` VARCHAR(255) NOT NULL,
  `fk_country_id` INT(11),
  PRIMARY KEY (`id`, `fk_country_id`),
  CONSTRAINT `country_id`
    FOREIGN KEY (`fk_country_id`)
    REFERENCES `country` (`country_id`)
    ON DELETE RESTRICT
    ON UPDATE RESTRICT)
ENGINE = InnoDB CHARSET = Latin1;

CREATE TABLE IF NOT EXISTS `Medium` (
  `id` INT(11) NOT NULL,
  `name` VARCHAR(255) NOT NULL,
  PRIMARY KEY (`id`))
ENGINE = InnoDB CHARSET = Latin1;


CREATE TABLE IF NOT EXISTS `artists_medium` (
  `artists_id` INT(11),
  `medium_id` INT(11),
  PRIMARY KEY (`artists_id`, `medium_id`),
  CONSTRAINT 
    FOREIGN KEY (`artists_id`)
    REFERENCES `artists` (`id`)
    ON DELETE CASCADE
    ON UPDATE CASCADE,
  CONSTRAINT 
    FOREIGN KEY (`medium_id`)
    REFERENCES `Medium` (`id`)
    ON DELETE CASCADE
    ON UPDATE CASCADE)
ENGINE = InnoDB CHARSET = Latin1;

CREATE TABLE IF NOT EXISTS `artists_residence` (
  `artists_id` INT(11),
  `city_id` INT(11),
  PRIMARY KEY (`artists_id`, `city_id`),
  CONSTRAINT 
    FOREIGN KEY (`artists_id`)
    REFERENCES `artists` (`id`)
    ON DELETE CASCADE
    ON UPDATE CASCADE,
  CONSTRAINT 
    FOREIGN KEY (`city_id`)
    REFERENCES `city` (`id`)
    ON DELETE CASCADE
    ON UPDATE CASCADE)
ENGINE = InnoDB CHARSET = Latin1;

我无法弄清楚最终查询中的失败。所有其他查询都成功并创建了表。我已经在各种变化中摆弄了那个查询,似乎没有什么能解决这个错误。香港专业教育学院删除了显式索引,改变了约束的顺序,检查了所有类型的比较。这是mysql基于我设计的模型导出的文件,因此我不确定为什么现在我收到此错误。请不要参考我对错误代码的引用或另一个也收到此错误代码的帖子,我知道什么可能导致错误,但我想知道是什么原因导致它。

1 个答案:

答案 0 :(得分:0)

在这种情况下 - 您正在创建以下外键

CONSTRAINT FOREIGN KEY (  `city_id` ) REFERENCES  `city` (  `id` ) ON DELETE CASCADE ON UPDATE CASCADE

虽然city表没有id主键,但是复合主键。

显然,2中唯一的一列不能保证值的唯一性,因此mysql限制你创建这样的FK。

因此,您必须更改city的PK或artists_residence的FK。