insert into table select * from table where primarykey=1
I just want to copy one row to insert into the same table (i.e., I want to duplicate an existing row in the table) but I want to do this without having to list all the columns after the "select", because this table has too many columns.
But when I do this, I get the error:
Duplicate entry 'xxx' for key 1
I can handle this by creating another table with the same columns as a temporary container for the record I want to copy:
create table oldtable_temp like oldtable;
insert into oldtable_temp select * from oldtable where key=1;
update oldtable_tem set key=2;
insert into oldtable select * from oldtable where key=2;
Is there a simpler way to solve this?
I would use below,
This solution showed above works perfect also for selected rows. For example I am creating demonstration rows for my nice2work project, and this works perfect.
I know it's an old question, but here is another solution:
This duplicates a row in the main table, assuming the primary key is auto-increment, and creates copies of linked-tables data with the new main table id.
Other options for getting column names:
-SHOW COLUMNS FROM
tablename
; (Column name: Field)-DESCRIBE
tablename
(Column name: Field)-SELECT column_name FROM information_schema.columns WHERE table_name = 'tablename' (Column name: column_name)
Create a table
Insert a row
Clone row insert above
Test
Here's an answer I found online at this site Describes how to do the above1 You can find the answer at the bottom of the page. Basically, what you do is copy the row to be copied to a temporary table held in memory. You then change the Primary Key number using update. You then re-insert it into the target table. You then drop the table.
This is the code for it:
I created the temporary table rescueteam. I copied the row from my original table fitnessreport4. I then set the primary key for the row in the temporary table to null so that I can copy it back to the original table without getting a Duplicate Key error. I tried this code yesterday evening and it worked.
This can be achieved with some creativity:
This will result in the new row getting an auto incremented id instead of the id from the selected row.