简体   繁体   中英

MySQL insert statement fails with foreign key constraint

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?

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.

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

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

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

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.

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 INTO alias ( alias , ref_links_id ) VALUES ("3334",4)

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