1

I'm trying to link 2 tables together in the database I created. but I'm getting #1452 - Cannot add or update a child row error.

interestingly, it allows me to establish a fk-pk relationship when the table is empty, but I get an error when I pass data to the table with csv. when I first set up relationships and then try to import the data, I get the error adding this time.

what would be the reason?

SQL Query:

ALTER TABLE `kickstarter` ADD  FOREIGN KEY (`country_num`) REFERENCES `kickstarter_countries`(`country_id`) ON DELETE RESTRICT ON UPDATE RESTRICT;

MySQL Output:

1452 - Cannot add or update a child row: a foreign key constraint fails (htimurat_data_analytics.#sql-f8c5_6a687, CONSTRAINT #sql-f8c5_6a687_ibfk_1 FOREIGN KEY (country_num) REFERENCES kickstarter_countries (country_id))

Lelio Faieta
  • 6,457
  • 7
  • 40
  • 74
Murat Kılınç
  • 175
  • 3
  • 16
  • Are you using the phpMyAdmin Designer interface to create the relationship or the Relation view tab under the table's structure area? – Isaac Bennetch Nov 19 '19 at 14:06
  • @Isaac Bennetch I also used the designer mode of phpmyadmin. but I get the same error there. my problem is not resolved. – Murat Kılınç Nov 21 '19 at 08:10
  • In that case, your problem doesn't seem to be related to phpMyAdmin. This is a duplicate of https://stackoverflow.com/a/56989783/2385479 - it looks like you are trying to enforce the relationship but don't match one or more of the values that should be in the parent table. – Isaac Bennetch Nov 23 '19 at 15:54
  • Exactly! I solved my problem. If there is data in one of the tables that are linked together, the other one must also have to link the tables. The problem is solved when I enter data into the table I want to link. @IsaacBennetch – Murat Kılınç Nov 25 '19 at 18:10
  • Glad that was the solution. I turned my comment in to an answer, which in the Stack Overflow universe means (if you wish,) you can mark it as accepted so others can benefit from this exchange. – Isaac Bennetch Nov 26 '19 at 15:43

1 Answers1

2

It looks like you are trying to enforce the relationship but don't match one or more of the values that should be in the parent table. The data that relates to each other must exist in both tables, otherwise you get the error message. You'll need to clean up the data in the tables before you can enforce the relationship.

Isaac Bennetch
  • 11,830
  • 2
  • 32
  • 43