2017-06-29 122 views
0

我有这两个简单的表简单的表格 - 错误1215:无法添加外键约束,

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:无法添加外键约束

回答

0

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

PRIMARY KEY(city_id_test,location_main_master_id)

所以,你的主表应该像

CREATE TABLE location_main_master(
location_main_master_id BIGINT(16)UNSIGNED NOT NULL,
city_id_test INT(10)UNSIGNED NOT NULL,
PRIMARY KEY(city_id_test,location_main_master_id),
UNIQUE KEY location_main_master_id_UNIQUE(location_main_master_id)
)ENGINE = INNODB DEFAULT CHARSET = utf8;

+0

参考:https://www.percona.com/blog/2017/04/06/dealing-mysql-error-code-1215-cannot-add-foreign-key-constraint/ 要点(6)。 – money

+0

或在city_id_test上添加一个密钥 –

+0

谢谢你们,明白了。 –

相关问题