I am trying to duplicate a row in my table, into another table. There query looks like this
INSERT INTO `quote_block_arc` (`id`,`quote_id`,`name`,`description`,`price`,`hours`,`days`,`total_hours`,`is_print`,`amends`) SELECT `id`,`quote_id`,`name`,`description`,`price`,`hours`,`days`,`total_hours`,`is_print`,`amends` FROM `quote_block` WHERE `quote_id` = '41'
However, it failing saving there is a duplicate key for this row, is there a way to ignore that warning and run the query?
This error occurs because you have specified one of the columns of your table to be
UNIQUE
. You cannot have 2 rows with the same value for this column. If you want to replace the existing row instead, useREPLACE
instead ofINSERT
. If you really want rows containing the same value for the column, remove theUNIQUE
modifier from that column.Using
INSERT IGNORE
as described in some of the other answers will prevent the error being issued, but will not update the table.Having a duplicate row in a table with a unique/primary constraint would violate its integrity. You should check what the key is and confirm if you actually need to copy it. For example, AUTO_INCREMENT primary keys are traditionally not inserted because the database will fill that for you automatically. I'd check the destination table
quote_block_arc
ifid
is AUTO_INCREMENT. IF it is, remove it from the INSERT and let MySQL insert it by itself.Using
INSERT IGNORE
will result in your row not being inserted. UseREPLACE
if you want to overwrite the duplicate key, but I do not recommend it over the method I've described earlier.You can perform
INSERT IGNORE
, orINSERT ... ON DUPLICATE KEY UPDATE
Another way is to check result of the query, if it's false - check the error, and if the error code is 1062 (duplicate entry) to continue execution as if there were no error.try
I recommend you get the highest
id
from the targetquote_block_arc
, you then add that to theid
in yourSELECT
subquery. That way, you know how to update any other related entries in other tables that reference those rows. If you were to let the RDBMS assign newid
s for you, all relation would be lost.