Friday, December 22, 2017

Duplicate / Copy rows/ records in the same MySQL table

I need to copy/duplicate a lot of rows. If you just export and import sql file it will not work as the table has auto increment id column. So I find an easy solution for my problem. I would like to duplicate a record in a table, but of course, the unique primary key needs to be updated.
First it need to create a temporary table and then update all id to null. then insert into table.

Here is an example query

CREATE TEMPORARY TABLE tmp SELECT * FROM sms_history WHERE date='2017-12-22';
UPDATE tmp SET id=NULL;
INSERT INTO sms_history SELECT * FROM tmp WHERE date='2017-12-22';
DROP TABLE tmp;

This is the most easy and fastest solution for this kind of problem.

No comments:

Post a Comment

Total Pageviews