开发者

Duplicating rows in a mysql table without enumerating fields

开发者 https://www.devze.com 2023-01-24 19:04 出处:网络
This mysql table has an autoincrement field. I want to duplicate some rows. I thought I will use a temporary table:

This mysql table has an autoincrement field. I want to duplicate some rows. I thought I will use a temporary table:

CREATE TEMPORARY TABLE tmptab SELECT * FROM mytab WHERE somecondition = 1;

Before copying the data back to mytab I can now do some updates in tmptab.

UPDATE tmptab ... /* some updates */;

Because mytab has an autoincrement field I cannot simply copy the contents of tmptab to mytab. One solution would be to enumarate fields (and omit the autoincrement field).

I am looking for a solution without开发者_开发百科 enumerating fields. This has advantages, for instance when fields will be added later.

I thougth I could erase the autoincrement field in tmptab (removing the autoincrement column) and then use a query similar to this one:

INSERT INTO mytab SELECT *  FROM tmptab;

Would this work? The autoincrement field in mytab should be set correctly. Or is there a better way to do it?


I thougth I could erase the autoindex field in tmptab (removing the autoindex column) and then use a query similar to this one

You need to use a command like this:

UPDATE tmptab SET key_column=NULL

When you insert NULLs back into the original table, it will generate new auto_increment ids.

You might need to add a command to drop the primary key index on the temp table for this to work.

0

精彩评论

暂无评论...
验证码 换一张
取 消