Importing a csv file causes a foreign key constraint - mysql

Hi I am trying to import a csv file in Mysql but i am getting an error saying that "Cannot add or update a child row: a foreign key constraint fails ".Why is this happening and how should i correct it???

One of the columns on the table you're importing data into has a relationship (a foreign key constraint) with another column on another table.
The file you have contains data on at least one column of one row that is not present on the associated column of that other table, thus violating that constraint.
You must identify the row of data that is failing to import. If the tool you're using does not identify the row, you can insert the rows one at a time to see at what point it fails.
Afterwards, you can either fix that row -- if it needs fixing -- or add the value that is being inserted into whatever related table.
The corrective action depends on whether the data you're trying to import is bad or the foreign table is missing something.

Related

need some explanation about foreign key constraint

I'm using symfony 4 and when I do links between tables there are indexes created. I do not understand how they work.
What is their purpose and why is it impossible to import data file into those files.
Is it possible to 'bypass' this mysql restriction and import data-files into mysql even if there is a constraint (without breaking the indexes)?
Thanks
MySQL is a relational database system. If there is a relationship between 2 tables, it is there for a reason. Think of your entities in Symfony. If one entity (a primary entity) has several related entities and those related entities can only exist if there is a primary entity, then the constraint must exist to prevent orphaned records.
For example:
Consider the relationship between companies and divisions. A company can have 0 or more divisions, but a division can only exist as a part of a company. In this case, a record in the division table would have a reference to a record in the company table. However, a record in a company table would have no direct reference in MySQL to any records in the division table.
To prevent a division from being created without a company, you cannot insert a row into the division table that does not reference a record in the company table.
To finally answer the question directly, you can only import data that does not reference the primary table by removing the foreign key constraint (this will not destroy the index). Keep in mind that this will likely result in records that are "orphaned" and do not fit the business model you are trying to create.
Rather than removing the foreign key constraint, you should first import the data to the referenced table (scoring?) and then update the data being imported to contain the correct ids to reference the primary table.
Based on the information in the image provided, each record in the file being imported should have a value for scoring_id that is equal to (presumably) the id field in the scoring table. If there is some other piece of data that can be used to link the 2 tables, use that and configure your entities appropriately.
Mysql FOREIGN KEY is used for data integrity. So what happens is you have a Foreign key which refers to column in another table .It's a way to link data relationships between tables
When Using Import if that key does not exist in the other table the mysql import will throw errors .
If you remove the FOREIGN KEY flag you would be able to import that table
refer to MYSQL manual
on Foreign Keys
Foreign keys will check if the other table has already that element that you try to enter.
What you can do for the import temporarily
use FOREIGN_KEY_CHECKS
Before the import run
SET FOREIGN_KEY_CHECKS=0;
and When it is finished
SET FOREIGN_KEY_CHECKS=1;
Or
use DISABLE KEYS:
ALTER TABLE table_name DISABLE KEYS;
and when the import is finished:
ALTER TABLE table_name ENABLE KEYS;
Of course you have to change table_name

How do I avoid foreign key constraint fail error -

I am currently using dreamweaver and I am trying to insert a record insertion wizard connected to a mysql server. However when I try to update the column I get a foreign key constraint fail and I can understand this is due to me creating a non existent foreign key.But how else can I use an input wizard.
database
Here is the data model.
The column I am trying to update is "kommentar" but it is not working, any ideas?
Tough to say with the info provided, but in all likelihood the value you're using in hotellid doesn't have a corresponding entry in the table hotell.
You could run the same wizard for the hotels and add a hotel with your desired hotelid, before inserting into kommentar

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

I'm new to MySQL and databases in general. I've been tasked with manually moving an old database to a new one of a slightly different format. The challenges include transferring certain columns from a table in one database to another database of a similar format. This is made further difficult in that the source database is MyISAM and the destination is InnoDB.
So I have two databases, A is the source and B is the destination, and am attempting to copy 'most' of a table to a similar table in the destination database.
Here is the command I run:
INSERT INTO B.article (id, ticket_id, article_type_id,
article_sender_type_id, a_from, a_reply_to, a_to, a_cc, a_subject,
a_message_id, a_in_reply_to, a_references, a_content_type, a_body,
incoming_time, content_path, valid_id, create_time, create_by,change_time,
change_by)
SELECT id, ticket_id, article_type_id, article_sender_type_id,
a_from, a_reply_to, a_to, a_cc, a_subject, a_message_id, a_in_reply_to,
a_references, a_content_type, a_body, incoming_time, content_path,
valid_id, create_time, create_by, change_time, change_by
FROM A.article
WHERE id NOT IN ( 1 );
Error:
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`helpdesk`.`article`, CONSTRAINT `FK_article_ticket_id_id` FOREIGN KEY (`ticket_id`) REFERENCES `ticket` (`id`))
The reason for making the command so wordy is that the source has several columns that were unnecessary and so were pruned out of the destination table. The WHERE id NOT IN ( 1 ) is there so that the first row is not copied (it was initialized in both databases and MySQL throws an error if they both have the same 'id' field). I can't tell by the error if it expects 'ticket_id' to be unique between rows, which it is not, or if it is claiming that a row does not have a ticket_id and so can not be copied which is what the error seems to most often be generated by.
I can post the tables in question if that will help answer, but I am unsure of the best way to do that, so some pointing in the right direction there would be helpful as well.
Posts I looked at before:
For forming the command
For looking at this error
Thanks!
You'll want to run a SHOW CREATE TABLE on your destination table:
SHOW CREATE TABLE `B`.`article`;
This will likely show you that there is a foreign key on the table, which requires that a value exist in another table before it can be added to this one. Specifically, from your error, it appears the field ticket_id references the id field in the ticket table. This introduces some complexity in terms of what needs to be migrated first -- the referenced table (ticket) must be populated before the referencing table (article).
Without knowing more about your tables, my guess is that you haven't migrated in the ticket table yet, and it is empty. You'll need to do that before you can fill in the B.article table. It is also possible that your data is corrupt and you need to find which ticket ID is present in the article data you're trying to send over, but not present in the ticket table.
Another alternative is to turn off foreign key checks, but if possible I would avoid that, since the purpose of foreign keys is to ensure data integrity.

how to repair data so foreign keys can be added back to database

I have just discovered my database which has been moved between a few servers in the last few months was, in one of the database dumps, converted to myisam and all the foreign key constraints nuked (not impressed). I've converted all the tables back to innodb with a php script but now I'm finding half the constraints are failing to add.
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`identicar2`.<result 2 when explaining filename '#sql-2a7_c0'>, CONSTRAINT `#sql-2a7_c0_ibfk_1` FOREIGN KEY (`feature_sk`) REFERENCES `tbl_feature_list` (`feature_sk`))
I'm lost now, I can't go through thousands of records manually. what is the best thing to do in order to get my database back into shape?
I can provide table structures if you want but I imagine any solution will be independant of the exact structure anyway
The simplest solution: (containing the obvious danger of losing data you may want to keep)
UPDATE table
SET fkColumn = NULL
WHERE fkColumn NOT IN (SELECT referenceColumn FROM referencedTable)
If you just want to find them:
SELECT *
FROM table
WHERE fkColumn NOT IN (SELECT referenceColumn FROM referencedTable)

foreign key constraint giving issue while inserting records

I m trying to import data from one table to another table across the schema.but foreign key constraint is giving issue.
Suppose i m having schema one and schema two.
schema one has tables -->
user
behavior
userbehavior(id from user and behavior table are foreign keys in
userbehavior table)
same way i have tables structure in schema two.
schema 2 has tables-->
user1
behavior1
userbehavior1(id from user and behavior table are foreign keys in userbehavior table)
I have successfully imported records from user to user1 and behavior to behavior1 but when I m trying to import data from userbehavior to userbehavior1 i m getting following error::
cannot add or update a child row.foreign key constraint fails.
wat could be an issue?
Thanks in advance.
You have inconsistent data, which the database refuses to import, and for a good reason.
I'd create TEMPORARY tables (i.e. tables that are automatically deleted after the session ends, import the data there, use a few queries that show me the rows from userbehaviour that violate the FOREIGN KEY constraint, clear these up manually and then use SELECT INTO to copy the data to the real tables.
cause : There is at least one row in table userbehaviour which have no parent in other table
todo: first remove all foreign key constraints from both schema and Insert and then set constraint back
In case of exporting
open exported sql file and write
SET FOREIGN_KEY_CHECKS=0; on the top of the file
and SET FOREIGN_KEY_CHECKS==1; on the bottom of file
or
export through phpMyAdmin then check Disable foreign key checks