foreign key constraint giving issue while inserting records - mysql

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

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 get MySQL tables to update each other?

I'm new to programming so please forgive my ignorance. I'm trying to get MySQL tables to update each other. For example: When I insert data into a Primary Key column in one table, it does not appear in it's Foreign Key column in another table.
Does anyone have any advice on this issue?
Thank you!
Additional Information: I used phpMyAdmin to create my tables and then added SQL code to create the Foreign Keys. Example of code is below.
ALTER TABLE CourseSchedule
ADD FOREIGN KEY (CourseId)
REFERENCES Course(CourseId)
I believe what we have here is a slight misunderstanding of the documentation.
For storage engines supporting foreign keys, MySQL rejects any INSERT
or UPDATE operation that attempts to create a foreign key value in a
child table if there is no a matching candidate key value in the
parent table.
When an UPDATE or DELETE operation affects a key value in the parent
table that has matching rows in the child table, the result depends on
the referential action specified using ON UPDATE and ON DELETE
subclauses of the FOREIGN KEY clause. MySQL supports five options
regarding the action to be taken, listed here
What your foreign key actually does is to make sure that you cannot insert values into your CourseSchedule table that do not correspond to an entry in the Courses table.
To give you an example, suppose you were to try to enter schedule a python course for every wednesday at 9:00 but you dont' actually have an entry for python in your Courses table. Then mysql will refuse to create that entry. Mysql cannot do the reverse. It doesn't know details about your python course. So it cannot automatically create a entry in the Courses table for you. Similarly, if oyu created an entr in the courses table. Mysql cannot automatically create a CourseSchedule for you because it doesn't know at what time it should be scheduled.

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.

Importing a csv file causes a foreign key constraint

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.

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)