I have a table "test" with an auto incremented id
and an arbitrary number of columns.
I want to make a copy of a row in this table with all columns the same except for the id
of course.
Is there a way to do this without naming all columns?
I thought INSERT... SELECT... ON DUPLICATE KEY
would help me until I realised that it never makes an INSERT ON DUPLICATE
, it just updates the existing row.
To select duplicate values, you need to create groups of rows with the same values and then select the groups with counts greater than one. You can achieve that by using GROUP BY and a HAVING clause.
A simple way is to open SSMS and Right click on database and go to Tasks > Import Data and follow the wizard to set source and destination. This way if data exists on different systems and even if you wish to change structure you can do. Also append, or cleanout data at same time from destination.
Let us say your table has following fields:
( pk_id int not null auto_increment primary key, col1 int, col2 varchar(10) )
then, to copy values from one row to the other row with new key value, following query may help
insert into my_table( col1, col2 ) select col1, col2 from my_table where pk_id=?;
This will generate a new value for pk_id
field and copy values from col1
, and col2
of the selected row.
You can extend this sample to apply for more fields in the table.
UPDATE:
In due respect to the comments from JohnP and Martin -
We can use temporary table to buffer first from main table and use it to copy to main table again. Mere update of pk reference field in temp table will not help as it might already be present in the main table. Instead we can drop the pk field from the temp table and copy all other to the main table.
With reference to the answer by Tim Ruehsen in the referred posting:
CREATE TEMPORARY TABLE tmp SELECT * from my_table WHERE ...; ALTER TABLE tmp drop pk_id; # drop autoincrement field # UPDATE tmp SET ...; # just needed to change other unique keys INSERT INTO my_table SELECT 0,tmp.* FROM tmp; DROP TEMPORARY TABLE tmp;
Hope this helps.
This works in MySQL all versions and Amazon RDS Aurora:
INSERT INTO my_table SELECT 0,tmp.* FROM tmp;
or
Setting the index column to NULL and then doing the INSERT.
But not in MariaDB, I tested version 10.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With