Mysql 简单表-错误1215:无法添加外键约束,

Mysql 简单表-错误1215:无法添加外键约束,,mysql,foreign-keys,Mysql,Foreign Keys,我有这两张简单的桌子 CREATE TABLE `location_main_master` ( `location_main_master_id` bigint(16) unsigned NOT NULL, `city_id_test` int(10) unsigned NOT NULL, PRIMARY KEY (`location_main_master_id`,`city_id_test`), UNIQUE KEY `location_main_master_id_UNI

我有这两张简单的桌子

CREATE TABLE `location_main_master` (
  `location_main_master_id` bigint(16) unsigned NOT NULL,
  `city_id_test` int(10) unsigned NOT NULL,
  PRIMARY KEY (`location_main_master_id`,`city_id_test`),
  UNIQUE KEY `location_main_master_id_UNIQUE` (`location_main_master_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE `location_sub_master` (
  `location_sub_master_id` bigint(16) unsigned NOT NULL,
  `city_id` int(10) unsigned NOT NULL,
  PRIMARY KEY (`location_sub_master_id`,`city_id`),
  UNIQUE KEY `location_sub_master_id_UNIQUE` (`location_sub_master_id`),
  KEY `fk_location_sub_master_city_id_idx` (`city_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
我正在尝试添加外键

ALTER TABLE `location_sub_master` 
ADD CONSTRAINT `fk_location_sub_city_id`
  FOREIGN KEY (`city_id`)
  REFERENCES `location_main_master` (`city_id_test`)
  ON DELETE NO ACTION
  ON UPDATE NO ACTION;
它给了我这个错误:

错误1215:无法添加外键约束


您必须更改主表中主键的顺序

主键(城市id测试、位置主id主id)

所以你的主桌应该是这样的

创建表位置\u主\u主(
位置\u主\u主\u id BIGINT(16)无符号非空,
城市id测试INT(10)无符号非空,
主键(城市id测试、位置主id主id),
唯一密钥位置\u主\u主\u id\u唯一(位置\u主\u主\u id)

)ENGINE=INNODB默认字符集=utf8

参考:第(6)点。或者在city_id_Test上添加一个键。谢谢你们,明白了。@GauravJ请接受答案,如果它解决了你们的问题,请向上投票,这样问题就不会一直没有答案。