简体   繁体   中英

error with alter table and foreign key

I have 2 tables :

  • Installers (Fields: id,company,country,experience,name)
  • Contacts (Fields: name,phone,address)

I would like to match both names, thereby I could click in one value of the name of Installers and it could show me the values of Contacts table.

However when I am trying to set up the foreign key (my child table will probably be Installers , as I have more tables like that and Contacts would be the parent.) It states this error:

query SQL:

ALTER TABLE `Installers` 
    ADD  FOREIGN KEY (`name`) 
         REFERENCES `SOLAR_PV`.`Contacts`(`name`) 
         ON DELETE CASCADE ON UPDATE CASCADE;

MySQL ha dicho: Documentación

1452 - Cannot add or update a child row: a foreign key constraint fails ( SOLAR_PV . #sql-32a_183 , CONSTRAINT #sql-32a_183_ibfk_1 FOREIGN KEY ( name ) REFERENCES Contacts ( name ) ON DELETE CASCADE ON UPDATE CASCADE)

Both tables are InnoDB and Contacts.name is indexed as well as Installers.name

Primary Key of Installers is id and Primary Key of Contacs is name.

Any idea about what would be the problem?

It seems your child table contains few records those don't have in master, you can check it by below query-

SELECT id FROM Installers ins 
LEFT JOIN SOLAR_PV.Contacts cnt ON ins.name=cnt.name 
WHERE cnt.name IS NULL;

Note: Assuming name is int type for better performance as it is primary key in one table.

If you get few records by above query then you can follow below 2 approach-

Approach1: You can either delete these records in child table or insert in master table also and then you can create relationship by this alter command.

Approach2: If you don't want to change in your tables existing data and still want to execute your alter query then use as per below-

SET FOREIGN_KEY_CHECKS=0;

ALTER TABLE `Installers` 
    ADD  FOREIGN KEY (`name`) 
         REFERENCES `SOLAR_PV`.`Contacts`(`name`) 
         ON DELETE CASCADE ON UPDATE CASCADE;

SET FOREIGN_KEY_CHECKS=1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM