1

What I want to do is put a Foreign Key from users_table column id into users_order table in the column user_id but when I try to do it says this. what did I do wrong or is there any other way to add foreign key to table in PhpMyAdmin ?

#1452 - Cannot add or update a child row: a foreign key constraint fails (`users`.`#sql-4830_792`, CONSTRAINT `#sql-4830_792_ibfk_1` FOREIGN KEY (`id`) REFERENCES `user_order` (`user_id`))

Users

Giorgos Myrianthous
  • 36,235
  • 20
  • 134
  • 156
Justin Junias
  • 493
  • 2
  • 5
  • 9
  • Can you write steps you are doing here? So I can understand what wrong you are doing. Have you made an `index` on 'user_id' column of 'user_order' table? – Himanshu Upadhyay Oct 25 '18 at 05:35
  • [Possible Duplicate]https://stackoverflow.com/questions/5005388/cannot-add-or-update-a-child-row-a-foreign-key-constraint-fails – DPS Oct 25 '18 at 05:53

3 Answers3

4

According to the docs,

For storage engines supporting foreign keys, MySQL rejects any INSERT or UPDATE operation that attempts to create a foreign key value in a child table if there is no a matching candidate key value in the parent table.

The error you see indicates that you are trying to add a new row to a child table, for which mo matching row is present in your parent table. To fix it, you can either add the row in your parent table before inserting a row in your child table, or remove NOT NULL constraints (if any) and insert a NULL value in the corresponding column. Once you do it, you will be able to add the foreign key constraint.

Giorgos Myrianthous
  • 36,235
  • 20
  • 134
  • 156
1

Your error said that the value that you are inserting into the foreign key does not exists in the parent table. so before insertion foreign value into child table make sure your value is in parent table

Zaynul Abadin Tuhin
  • 31,407
  • 5
  • 33
  • 63
-2

The value should be the same in the primary and index key columns.

  • I meant that the index columns values must in the primary to make a relation in between like if index value is 8 then 8 must be in the primary column too – sidra aslam Feb 20 '23 at 12:37