[英]Mysql:Cannot add or update a child row: a foreign key constraint fails
First of all, i know there are many posts about this subject but the ones i checked didnt help me so i wanted to post my problem. 首先,我知道有很多关于这个主题的帖子,但是我检查过的帖子并没有帮助我,所以我想发布我的问题。
I am building a website that people can register as user then fill some different forms for me. 我正在建立一个网站,人们可以注册为用户,然后为我填写一些不同的表格。 I have 2 table one is "user" and the other one is "form" table. 我有2个表,一个是“用户”表,另一个是“表单”表。 In user table i have user_id which is auto_incremented and this id connected to "form" table as foreign key. 在用户表中,我有一个user_id,它是auto_incremented,并且此ID作为外键连接到“ form”表。 I want to see which user filled forms via user_id. 我想看看哪个用户通过user_id填写了表格。 When i try to register filled form to database i get "Cannot add or update a child row: a foreign key constraint fails" message. 当我尝试将填写好的表单注册到数据库时,出现“无法添加或更新子行:外键约束失败”消息。 How can i fix this? 我怎样才能解决这个问题?
If you have set the user_id on on your form table as a foreign key pointing at the user_id in the user table, you must supply a valid user_id when you insert the form row. 如果您在表单表上将user_id设置为指向用户表中的user_id的外键,则在插入表单行时必须提供有效的user_id。
You could set the user_id field on the form table to be allowed to be NULL this will mean it does not have to be set. 您可以将表单表上的user_id字段设置为允许为NULL,这意味着不必进行设置。
您正在尝试将一些数据添加到外键列中,而其他表中没有相同的数据。
This mostly happens when there is a data in table and you want to create/ edit/ delete a foreign_key 当表中有数据并且您要创建/编辑/删除foreign_key 时,通常会发生这种情况
OR 要么
the field that you want to make it foreign_key is not the same format with Table field 您要使其成为Foreign_key的字段与Table字段的格式不同
solution: 解:
You have to make a 你必须做一个
1)backup or copy of you data 1)备份或复制您的数据
2)remove the foreign_keys 2)删除foreign_keys
3)and Truncate data from table 3)并截断表中的数据
4)Finally re attach the foreign_keys 4)最后重新附加foreign_keys
5)update your data 5)更新您的数据
I hope it helps 希望对您有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.