2017-06-29 1 views
0

Ich habe diese beiden einfachen Tabelleeinfache Tabellen -Fehler 1215: Kann nicht über Fremdschlüssel hinzufügen,

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; 

ich einen Fremdschlüssel

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; 

hinzufügen bin versucht, es mir diese Fehlermeldung geben:

ERROR 1215: Kann nicht fremd hinzufügen Schlüsseleinschränkung

Antwort

0

Sie müssen die Reihenfolge Ihres Primärschlüssels in der Master-Tabelle ändern.

PRIMARY KEY (city_id_test, location_main_master_id)

So Ihre Haupttabelle wie

CREATE TABLE location_main_master aussehen sollte (
location_main_master_id BIGINT (16) UNSIGNED NOT NULL,
city_id_test INT (10) UNSIGNED NOT NULL,
PRIMÄRSCHLÜSSEL (city_id_test, location_main_master_id),
UNIQUE KEY location_main_master_id_UNIQUE (location_main_master_id)
) ENGINE = INNODB DEFAULT CHARSET = utf8;

+0

Referenz: https://www.percona.com/blog/2017/04/06/dealing-mysql-error-code-1215-cannot-add-foreign-key-constraint/ Punkt (6). – money

+0

Oder fügen Sie einen Schlüssel auf city_id_test –

+0

Danke Jungs, hab es. –

Verwandte Themen