We're having weird errors on our production environment.
The error is:
MySQLIntegrityConstraintViolationException:
Cannot add or update a child row:
a foreign key constraint fails
('MSeHA_BARTLETT'.'document_version',
CONSTRAINT 'document_version_ibfk_1'
FOREIGN KEY ('document_id')
REFERENCES 'document' ('id')
ON DELETE CASCADE ON UPDATE CASCADE).
On SQL:
INSERT INTO 'document_version' SET
'document_id'='2002069',
'type_id'='2',
'subtype_id'='119091',
'status_id'='4',
'event_timestamp'='2012-02-08 15:02:00',
'provider_id'='1056'
ON DUPLICATE KEY UPDATE
'id'=LAST_INSERT_ID('id') ,
'type_id'='2',
'subtype_id'='119091',
'status_id'='4',
'provider_id'='1056'
With my knowledge of mysql and foreign keys, i had a few assumptions.
the table was locked. I used the cli to do this manually via locking/unlocking tables mid transaction, however it just waited patiently until the table was unlocked and finished...so no go.
so document_version is referencing document which has to be unique. Maybe 2 transactions at the same time try to insert the same document and mysql would give back different ids. Thsi would mean one would work fine, but the 2nd transaction would try to finish, but document would fail unique key constraints, making the document_id invalid? Thus failing the foreign key? Again, I re-enacted this via cli by starting 2 transactions, and letting them both insert the same row into document. Again mysql waited patiently on transaction #2 until the 1st transaction finished before letting it proceed and errored. Not the problem.
I'm at a loss. Any ideas are appreciated.
Related
I was wondering if there was an option to check the referntial integrity of my database without checking everything manually. I must mention that I'm completely new to SQL and have the task to check the referential integrity.
With the search I found this question:
how to find records that violate referential integrity
which was already helpful, but I got quite a lot of tables and I was wondering if there was a faster way than writting hundreds of the querys in the format of the question I found.
Thanks for helping,
Yíu
EDIT:
I know that most databases check that automatically, but I'm a student and the task says
"These scripts should illustrate updating and referential integrity of your database.
! Please point explicitly where you check referential integrity (adding rows, modifying rows, deleting rows). "
So I guess I have to check it manually.
The most databases check referencing, like MySQL too. So have a look at FOREIGN KEY and REFERENCES command
http://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html
Sample from MySQL page
CREATE TABLE parent (
id INT NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (
id INT,
parent_id INT,
INDEX par_ind (parent_id),
FOREIGN KEY (parent_id)
REFERENCES parent(id)
ON DELETE CASCADE
) ENGINE=INNODB;
Child automatically check and need parent row. If you delete parents, all child rows will deleted to (ON DELETE CASCADE).
I am importing a database from an SQL dump and I get this error:
Cannot add or update a child row: a foreign key constraint fails
(`database_name`.`#sql-808_37`, CONSTRAINT `FK_z_log_zemail` FOREIGN KEY (`ID_evn`)
REFERENCES `z_event` (`ID_evn`) ON DELETE SET NULL)
Operation failed with exitcode 1"
I know that it means that the foreign key in the child table is not in the parent table z_event, hence the error.
Question:
Was the process of importing the sql dump aborted from this line on? (Operation failed with exitcode 1)
Is there any "clean" way of bypassing this error without compromising the data integrity? Or any other solutions that do not involve removing the constraint?
Why does this happens? Some bad relationship settings between tables? Like when something was deleted from the parent table, the child table was not updated?
Is there any chance that the sql dump is corrupted? Or is this error pretty common? I am asking to know if I should be worried or not..
Answers:
It depends on how are you restoring the database. If you are running a script making inserts it may have skipped the problem and continue, but if you are making a bulk insert (with COPY) it will fail completly.
No way to clean bypass.
Maybe the dump is in wrong order. The table needed is below (or after) the table that references it. In your case you have to ensure that z_event is loaded first.
Maybe it is corrupted, but in my experience the 3rd is the usual explanation.
After several days of application running successfully I suddenly see errors:
Cannot add or update a child row: a foreign key constraint fails
If I run the SQL outside the context of the application sure enough it fails.
The data looks good and the constraints worked previously. Further, if I drop the constraints and add them back as they were everything works again.
I have to go through and drop/add the constraints until everything works again.
Any ideas of what I may be doing wrong here or quick way to recreate all FK's quickly?
Example FK Contraints:
CONSTRAINT `FKC92ACD965FF39405` FOREIGN KEY (`foodItem_id`) REFERENCES `FoodItem` (`id`),
CONSTRAINT `FKC92ACD966C592425` FOREIGN KEY (`meal_id`) REFERENCES `Meal` (`id`)
Example SQL:
into MealItem
(foodItem_id, meal_id, quantity)
values(150, 277, 0.375)
Thanks,
Bruce
I have never heard of a case where InnoDB foreign keys work intermittently and need to be dropped and recreated. And I don't recommend you adopt a habit of running unnecessary ALTER TABLE statements.
The more likely explanation is that you first tried to insert a row to MealItem before the referenced rows in either FoodItem or Meal have been inserted.
You can find more information on the exact foreign key constraint that was violated, by running:
mysql> pager less
mysql> SHOW ENGINE INNODB STATUS;
Look for the subsection something like the following:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
...some information about the transaction and thread context...
insert into MealItem (foodItem_id, meal_id, quantity) values(150, 277, 0.375)
Foreign key constraint fails for table `mydatabase/MealTime`:
CONSTRAINT `FKC92ACD965FF39405` FOREIGN KEY (`foodItem_id`) REFERENCES `FoodItem` (`id`),
Trying to add in child table, in index `foodItem_id` tuple:
DATA TUPLE: 2 fields; ...some binary description of the row you tried to insert...
But in parent table `mydatabase/FoodItem`, in index `PRIMARY`,the closest match we can find is record:
...some binary description of MySQL's guess at a row near the one that's missing...
I've mocked up this example, and omitted some of the less useful stuff. This diagnostic information is relatively easy to read (compared to some). From this you can discover exactly which constraint had a conflict, and which parent table is missing the needed row.
Re your comment:
You wouldn't happen to be using OS X and MySQL between 5.5.8 and 5.5.12? I found the error you mention in reference to a bug that appeared in a specific version of MySQL, and only on OS X. Details here: http://bugs.mysql.com/bug.php?id=60309
The bug should be fixed if you upgrade to at least 5.5.13, or preferably upgrade to the latest
(5.5.32 as of June 2013).
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)
Error: cannot add or update a child row: foreign key constraint fails
Following is the code that is creating the error:
ALTER TABLE 'catalog_eav_attribute'
ADD CONSTRAINT 'FK_CATALOG_EAV_ATTRIBUTE_ID'
FOREIGN KEY ('attribute_id') REFERENCES 'eav_attribute' ('attribute_id)'
ON DELETE CASCADE ON UPDATE CASCADE;
I uploaded the Structure of SQL and its has no issue , but when i insert the data i am getting the above related error. I read somewhere and i predict its because of lousy data.What are the other possibilities for the error ? Any suggestions or solution will be great.
"For storage engines other than InnoDB, MySQL Server parses the FOREIGN KEY syntax in CREATE TABLE statements, but does not use or store it."
From: http://dev.mysql.com/doc/refman/5.5/en/ansi-diff-foreign-keys.html
I'm not sure, but if your table is MyISAM and not InnoDB, your syntax might not work.
The error message means whatever number you're trying to put into the attribute_id column doesn't yet exist in the eav_attribute.attribute_id column.
Can you insert a value that does already exist in eav_attribute.attribute_id? (You probably can.)
Can you provoke the same error by trying to insert a value that doesn't exist in eav_attribute.attribute_id?
Reconcile the differences, and you're done. You need to determine which attribute ids don't exist in eav_attribute.attribute_id, and fix that.