I have a table Eg- tab . What I am trying to do is copying a row with an autoincrement column ID=1 and insert the data into same table with a row and column ID=2.
Using MySql. How can I do this in a single query?Please help
I have a table Eg- tab . What I am trying to do is copying a row with an autoincrement column ID=1 and insert the data into same table with a row and column ID=2.
Using MySql. How can I do this in a single query?Please help
I tend to use a variation of what mu is too short posted:
As long as the tables have identical fields (excepting the auto increment on the log table), then this works nicely.
Since I use stored procedures whenever possible (to make life easier on other programmers who aren't too familiar with databases), this solves the problem of having to go back and update procedures every time you add a new field to a table.
It also ensures that if you add new fields to a table they will start appearing in the log table immediately without having to update your database queries (unless of course you have some that set a field explicitly)
Warning: You will want to make sure to add any new fields to both tables at the same time so that the field order stays the same... otherwise you will start getting odd bugs. If you are the only one that writes database interfaces AND you are very careful then this works nicely. Otherwise, stick to naming all of your fields.
Note: On second thought, unless you are working on a solo project that you are sure won't have others working on it stick to listing all field names explicitly and update your log statements as your schema changes. This shortcut probably is not worth the long term headache it can cause... especially on a production system.
Dump the row you want to sql and then use the generated SQL, less the ID column to import it back in.
Use
INSERT ... SELECT
:where
c1, c2, ...
are all the columns exceptid
. If you want to explicitly insert with anid
of 2 then include that in your INSERT column list and your SELECT:You'll have to take care of a possible duplicate
id
of 2 in the second case of course.For a quick, clean solution that doesn't require you to name columns, you can use a prepared statement as described here: https://stackoverflow.com/a/23964285/292677
If you need a complex solution so you can do this often, you can use this procedure:
You can run it with:
Examples
DISCLAIMER: This solution is only for someone who will be repeatedly duplicating rows in many tables, often. It could be dangerous in the hands of a rogue user.
IMO, the best seems to use sql statements only to copy that row, while at the same time only referencing the columns you must and want to change.
See also av8n.com - How to Clone an SQL Record
Benefits:
your_table
in one atomic operation.