Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP MySQL Copy a row within the same table... with a Primary and Unique key

Tags:

My table has two keys, one is an auto incrementing id (PRIMARY), the other is the name of the item (UNIQUE).

Is it possible to duplicate a row within this same table? I have tried:

INSERT INTO items SELECT * FROM items WHERE id = '9198' 

This gives the error Duplicate entry '9198' for key 'PRIMARY'

I have also tried:

INSERT INTO items SELECT * FROM items WHERE id = '9198' ON DUPLICATE KEY UPDATE id=id+1 

Which gives the error Column 'id' in field list is ambiguous

And as far as the item name (UNIQUE) field goes, is there a way to append (Copy) to the item name, since this field must also be unique?

like image 865
Norse Avatar asked Jul 26 '12 01:07

Norse


People also ask

How do I copy a row in PHP?

Once it's enabled, select a row and then in “Copy Row” button in the footer. It will duplicate the selected row in the database table and even return the auto-incremented ID. Note that this feature requires the primary key is an auto-increment type.


1 Answers

Select all columns explicitly, except the id column:

INSERT INTO items (col1, col2, ..., coln) SELECT col1, col2, ..., coln FROM items WHERE id = '9198' 

Your next question will probably be:

Is there a way to do this without listing all the columns explicitly?

Answer: No, I don't think so.

like image 74
Mark Byers Avatar answered Sep 28 '22 03:09

Mark Byers