2

I have this statement:

INSERT INTO `alias`( `alias`, `ref_links_id`) VALUES ("3334",4)

And I get this error:

Cannot add or update a child row: a foreign key constraint fails 

(`bestr_main`.`alias`, CONSTRAINT `alias_ibfk_1` FOREIGN KEY (`ref_links_id`) 

REFERENCES `links` (`link_id`) ON DELETE CASCADE ON UPDATE CASCADE)

The alias table is connected to link table with a foreign key. Why do I get this error when inserting a record?

I see now.. I tried to change the link between the keys to another table and I get this:

  1452 - Cannot add or update a child row: a foreign key constraint fails 

  (`bestr_main`.<result 2 when explaining filename '#sql-73c_38e0'>, CONSTRAINT 

 `#sql-73c_38e0_ibfk_1` FOREIGN KEY (`ref_links_id`) REFERENCES `refs` (`ref_id`) 

 ON DELETE CASCADE ON UPDATE C) 

What does that say?

3
  • 1
    Error itself tells the reason Commented Oct 9, 2012 at 10:15
  • Please, add which foriegn key is avialable in primary key table, Otherwise remove foriegn key from table... Commented Oct 9, 2012 at 10:18
  • Please start inserting values from the parent table which has referred , because of the parent table does'nt exist with the values it may results with above mentioned errors. Commented Oct 9, 2012 at 10:33

6 Answers 6

2

Read the error

FOREIGN KEY (ref_links_id) REFERENCES links (link_id))

Means

`links`.link_id  (Parent)

`alias`.ref_links_id (Child)

and no child exist without parent. so first check parent table for the value which you are inserting into child table

Sign up to request clarification or add additional context in comments.

Comments

1

You need to have a link_id with value 4 in your links table, if you wanna insert a 4 in alias.ref_links_id.

Create it in the links table first if it doesn't exist.

Comments

1

the link table doesn't have the value '4'. Please check the link table value, that it has the value '4'.

Comments

1
if((select count(*) from primaty_table where pk_id=4) > 0)
{
INSERT INTO `alias`( `alias`, `ref_links_id`) VALUES ("3334",4)
}

Comments

1

Maybe someone will find this, my problem was that in my MySQL script I had Engine = MyISAM; instead of InnoDB. changed Engine = InnoDB; and it worked.

Comments

-1

ref_links_id 4 will be already exist in the table alias. You can not insert duplicate value for foreign key constraint.

If you want to delete foreign key,

ALTER TABLE `alias` DROP FOREIGN KEY ref_links_id;  

Then try INSERT INTOalias(alias,ref_links_id) VALUES ("3334",4)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.