Why in MySQL, INSERT IGNORE INTO does not change the foreign key constraint errors into warnings?
I’m trying to insert a number of records into a table and I expect MySQL to leave out the ones that result in error, any error, and insert the rest. Does anyone have any suggestions?
And the SET FOREIGN_KEY_CHECKS = 0; is not my answer. Because I expect the rows which defy the constraints not to be inserted at all.
Thanks
[NEW ANSWER]
Thanks to @NeverEndingQueue for bringing this up. It seems MySQL has finally fixed this issue. I’m not sure which version this problem was first fixed in, but right now I tested with the following version and the problem is not there anymore:
To be clear:
mysql> INSERT IGNORE INTO child -> VALUES -> (NULL, 1) -> , (NULL, 2) -> , (NULL, 3) -> , (NULL, 4) -> , (NULL, 5) -> , (NULL, 6); Query OK, 4 rows affected, 2 warnings (0.03 sec) Records: 6 Duplicates: 2 Warnings: 2To better understand the meaning of this last query and why it shows the problem is fixed, please continue with the old answer below.
[OLD ANSWER]
My solution is a work around to the problem and the actual solution will always be fixing the problem within the MySQL itself.
The following steps solved my problem:
a. Consider having the following tables and data:
b. Now we need to delete some of the rows to demonstrate the problem:
c. PROBLEM: The problem arises when you try to insert the following child rows:
Even though the
IGNOREkeyword is used, but MySQL cancels the the requested operation because the generated error is not turned into warning (as it supposed to). Now that the problem is obvious, let’s see how can we execute the last insert into statement without facing any error.d. SOLUTION: I’m going to wrap the insert into statement by some other constant statements which are neither dependent on the records inserted, nor on their number.
I know that this is not optimum but as long as MySQL has not fixed the problem, this is the best I know. Especially since all the statements can be executed in one request if you use mysqli library in PHP.