Copy row but with new id

Mysql

Mysql Problem Overview


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.

Mysql Solutions


Solution 1 - Mysql

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.

Solution 2 - Mysql

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.

Solution 3 - Mysql

THIS WORKS FOR DUPLICATING ONE ROW ONLY

  • Select your ONE row from your table
  • Fetch all associative
  • unset the ID row (Unique Index key)
  • Implode the array[0] keys into the column names
  • Implode the array[0] values into the column values
  • Run the query

The code:

 $qrystr = "SELECT * FROM mytablename  WHERE id= " . $rowid;
 $qryresult = $this->connection->query($qrystr);
 $result = $qryresult->fetchAll(PDO::FETCH_ASSOC);
 unset($result[0]['id']); //Remove ID from array
 $qrystr = " INSERT INTO mytablename";
 $qrystr .= " ( " .implode(", ",array_keys($result[0])).") ";
 $qrystr .= " VALUES ('".implode("', '",array_values($result[0])). "')";
 $result = $this->connection->query($qrystr);
 return $result;

Of course you should use PDO:bindparam and check your variables against attack, etc but gives the example

additional info

If you have a problem with handling NULL values, you can use following codes so that imploding names and values only for whose value is not NULL.

foreach ($result[0] as $index => $value) {
    if ($value === null) unset($result[0][$index]);
}

Solution 4 - Mysql

SET @table = 'the_table';
SELECT GROUP_CONCAT(IF(COLUMN_NAME IN ('id'), 0, CONCAT("\`", COLUMN_NAME, "\`"))) FROM INFORMATION_SCHEMA.COLUMNS
                  WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = @table INTO @columns;
SET @s = CONCAT('INSERT INTO ', @table, ' SELECT ', @columns,' FROM ', @table, ' WHERE id=1');
PREPARE stmt FROM @s;
EXECUTE stmt;

Solution 5 - Mysql

depending on how many columns there are, you could just name the columns, sans the ID, and manually add an ID or, if it's in your table, a secondary ID (sid):

insert into PROG(date, level, Percent, sid) select date, level, Percent, 55 from PROG where sid = 31 Here, if sid 31 has more than one resultant row, all of them will be copied over to sid 55 and your auto iDs will still get auto-generated. for ID only: insert into PROG(date, level, Percent, ID) select date, level, Percent, 55 from PROG where ID = 31 where 55 is the next available ID in the table and ID 31 is the one you want to copy.

Solution 6 - Mysql

I am using a temporary table:

CREATE TEMPORARY TABLE tmp SELECT * FROM sitelog WHERE 1=1;
ALTER TABLE tmp DROP COLUMN `ID`;
INSERT INTO sitelog SELECT 0, tmp.* FROM tmp;
DROP TEMPORARY TABLE tmp;

Solution 7 - Mysql

INSERT into table_name (  
    `product_id`, 
    `other_products_url_id`, 
    `brand`, 
    `title`, 
    `price`, 
    `category`, 
    `sub_category`, 
    `quantity`, 
    `buy_now`, 
    `buy_now_url`, 
    `is_available`, 
    `description`, 
    `image_url`, 
    `image_type`, 
    `server_image_url`, 
    `reviews`, 
    `hits`, 
    `rating`, 
    `seller_name`, 
    `seller_desc`, 
    `created_on`, 
    `modified_on`, 
    `status`) 
SELECT 
    `product_id`, 
    `other_products_url_id`, 
    `brand`, 
    `title`, 
    `price`, 
    `category`, 
    `sub_category`, 
    `quantity`, 
    `buy_now`, 
    concat(`buy_now_url`,'','#test123456'), 
    `is_available`, 
    `description`, 
    `image_url`, 
    `image_type`, 
    `server_image_url`, 
    `reviews`, 
    `hits`, 
    `rating`, 
    `seller_name`, 
    `seller_desc`, 
    `created_on`, 
    `modified_on`, 
    `status` 
FROM `table_name` WHERE id='YourRowID';

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMartinView Question on Stackoverflow
Solution 1 - MysqlRavinder ReddyView Answer on Stackoverflow
Solution 2 - MysqlrcalvachiView Answer on Stackoverflow
Solution 3 - MysqlUraniumSteelView Answer on Stackoverflow
Solution 4 - MysqlDamibu LtdView Answer on Stackoverflow
Solution 5 - Mysqlsukebe7View Answer on Stackoverflow
Solution 6 - MysqlTalelView Answer on Stackoverflow
Solution 7 - MysqlAshuView Answer on Stackoverflow