开发者

Easiest Way Of Copying a Row in MySQL

what's the easiest way of to clone a row with a different ID in MySQL.

For example:

Products

product_id  name  price
------------------------
1           a     10
2           b     15

It looks like weird, but I need to clone product with id = 1. So the table will look like:

Products

product_id  name  price
------------------------
1           a     10
2           b     15
3          开发者_StackOverflow a     10


You can use subqueries:

   INSERT INTO 
          donation (name,price) 
   SELECT name,price
     FROM donation 
    WHERE product_id = 1


INSERT INTO Products (name, price) VALUES ((SELECT name FROM Products WHERE product_id = 1), (SELECT price FROM Products WHERE product_id = 2));


INSERT INTO Products (name, price)
VALUES 
((SELECT name, price 
    FROM Products  
   WHERE product_id = 1));


If you want to clone a row with a single SQL statement and can't or don't want to list all the values but there is a primary key you can use:

INSERT INTO Products
 SELECT *
  FROM Products
  WHERE product_id = 1
 UNION ALL
  SELECT *
   FROM Products
   WHERE product_id = 1
ON DUPLICATE KEY UPDATE product_id=(SELECT MAX(product_id)+1 FROM Products);

This tries to insert two copies of the row into the databse and when the first row insert fails due to a duplicate product_id it uses ON DUPLICATE KEY to update the existing row in the table to the next available product_id, which leaves the original product_id available for when the second row is inserted.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜