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'm assuming you want the new record to have a new
primarykey
? Ifprimarykey
isAUTO_INCREMENT
then just do this:...where
col1, col2, col3, ...
is all of the columns in the table except forprimarykey
.If it's not an
AUTO_INCREMENT
column and you want to be able to choose the new value forprimarykey
it's similar:...where
567
is the new value forprimarykey
.For a very simple solution, you could use PHPMyAdmin to export the row as a CSV file then simply import the amended CSV file. Editing the ID/primarykey column to show no value before you import it.
Then at the bottom of the page:
Where is says "Export" simply export, then edit the csv file to remove the primarykey value, so it's empty, and then just import it into the database, a new primarykey will be assigned on import.
You could also try dumping the table, finding the insert command and editing it:
The
--skip-extended-insert
gives you one insert command per row. You may then find the row in your favourite text editor, extract the command and alter the primary key to "default".If your table's primary key field is an auto increment field, then you can use query with columns. For example, your table named
test_tbl
has 3 fields asid, name, age
.id
is a primary key field and auto increment, so you can use the following query to duplicate the row:This query results in duplicating every row.
If your table's primary key field is not an auto increment field, then you can use the following method:
The result of this query is a duplicate row of
id=19
inserted asid=20
.I might be late in this, but I have a similar solution which has worked for me.
This way I don't need to create a temporary table and etc. As the row is copied in the same table the
Max(PK)+1
function can be used easily.I came looking for the solution of this question (had forgotten the syntax) and I ended up making my own query. Funny how things work out some times.
Regards
This procedure assumes that:
Of course this is not perfect, but in certain (probably most) cases it will work.