How to Deal with Duplicate Primary Keys on MySQL
Recently, I came across with a problem where I had to copy and insert some MySQL data from one database to another.
The issue regarded the same table structure in both databases, but with different data content in each. It was vital not to lose any information when importing the dump from one table to the other.
One of the most important details was that it was possible to have the same tuple repeated in both tables and I could not afford overwriting any content.
So, here follows the command used:
mysqldump -u user -p --no-create-info --insert-ignore mydatabase mytable > file.dump
The --no-create-info makes sure no DROP or CREATE info are added, so your table is not deleted and recreated and you don't lose any information.
With the --insert-ignore parameter, the data is inserted with the INSERT IGNORE method. Using so, when trying to insert a tuple with an already existent primary key it is simply ignored. The duplicated key tuple is discarded and the previous existent tuple remains.
Another useful command may be the INSERT ... ON DUPLICATE KEY UPDATE, that also, as the name suggests, deals with duplicated keys. This clause updates the value of the previous existing key in case of conflicts, so it can insert the new tuple.
For example if "myvalue" is a primary key, you can set:
INSERT INTO mytable (myvalue) VALUES (10)
ON DUPLICATE KEY UPDATE myvalue=myvalue+1;
ON DUPLICATE KEY UPDATE myvalue=myvalue+1;
Good job and thanks for sharing such a good blog You’re doing a great job. Keep it up !!
ReplyDeleteit was so good to read and useful to improve my knowledge as updated one, keep blogging.
Angular js Training in Chenai
Angular js Training in Velachery
Angular js Training in Tambaram
Angular js Training in Porur
Angular js Training in Omr
Angular js Training in Annanagar
nice
ReplyDeleteJava course in chennai
python course in chennai
web designing and development course in chennai
selenium course in chennai
digital-marketing seo course in chennai
Very nice and more informative article. amazon web services aws training in chennai
ReplyDeletemicrosoft azure course in chennai
workday course in chennai
android course in chennai
ios course in chennai
Thanks for the Article. Really a great one. Very informative and useful!! Appreciate your time and effort for posting this. Grateful
ReplyDeleteIELTS Coaching in chennai
German Classes in Chennai
GRE Coaching Classes in Chennai
TOEFL Coaching in Chennai
Spoken english classes in chennai | Communication training