简体   繁体   English

MySQL 插入语句因外键约束而失败

[英]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 . 如果要在alias.ref_links_id插入4,则需要在links表中具有一个值为4的link_id。

Create it in the links table first if it doesn't exist. 如果它不存在,请首先在links表中创建它。

the link table doesn't have the value '4'. 链接表的值不为“ 4”。 Please check the link table value, that it has the value '4'. 请检查链接表值,该值是否为'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;也许有人会发现这个,我的问题是在我的 MySQL 脚本中我有 Engine = MyISAM; instead of InnoDB.而不是 InnoDB。 changed Engine = InnoDB;更改引擎 = InnoDB; and it worked.它奏效了。

ref_links_id 4 will be already exist in the table alias . ref_links_id 4将已经存在于表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) 然后尝试INSERT INTO别名( alias , ref_links_id ) VALUES ("3334",4)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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