MySQL:外键约束不正确

时间:2016-11-28 07:34:48

标签: mysql sql

我使用的是MySQL数据库,有以下3个表:

map_range enter image description here

map_location(加入表格) enter image description here

位置 enter image description here

我正在尝试添加一些外键。

    ALTER TABLE `www`.`map_location` 
ALTER TABLE `www`.`map_location` 
ADD INDEX `fk_map_location_indx` (`LOC_ID` ASC);
ALTER TABLE `www`.`map_location` 
ADD CONSTRAINT `fk_map_loc_map`
  FOREIGN KEY (`MAP_ID`)
  REFERENCES `www`.`map_location` (`MAP_ID`)
  ON DELETE NO ACTION
  ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_map_loc_location`
  FOREIGN KEY (`LOC_ID`)
  REFERENCES `www`.`location` (`ID`)
  ON DELETE NO ACTION
  ON UPDATE NO ACTION;

但是我收到以下错误:

Operation failed: There was an error while applying the SQL script to the database.
    ERROR 1025: Error on rename of '.\www\#sql-ea0_2b8' to '.\www\map_location' (errno: 150 - Foreign key constraint is incorrectly formed)
    SQL Statement:
    ALTER TABLE `www`.`map_location` 
    ADD CONSTRAINT `fk_map_loc_map`
      FOREIGN KEY (`MAP_ID`)
      REFERENCES `www`.`map_location` (`MAP_ID`)
      ON DELETE NO ACTION
      ON UPDATE NO ACTION,
    ADD CONSTRAINT `fk_map_loc_location`
      FOREIGN KEY (`LOC_ID`)
      REFERENCES `www`.`location` (`ID`)
      ON DELETE NO ACTION
      ON UPDATE NO ACTION

enter image description here

任何想法都赞赏。

1 个答案:

答案 0 :(得分:1)

您正在自我引用相同的表格和列 你的意思是location而不是map_location

ALTER TABLE `www`.`map_location`
ADD CONSTRAINT... FOREIGN KEY (`MAP_ID`)
REFERENCES `www`.`map_location` (`MAP_ID`)