在 MySQL 中复制行的最简单方法

发布于 2024-11-17 15:59:54 字数 391 浏览 0 评论 0原文

在 MySQL 中克隆具有不同 ID 的行的最简单方法是什么。

例如:

Products

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

它看起来很奇怪,但我需要使用 id = 1 克隆产品。因此该表将如下所示:

产品

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

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           a     10

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

夜巴黎 2024-11-24 15:59:54

您可以使用子查询

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

You can use subqueries:

   INSERT INTO 
          donation (name,price) 
   SELECT name,price
     FROM donation 
    WHERE product_id = 1
或十年 2024-11-24 15:59:54

INSERT INTO Products (名称, 价格) VALUES ((从产品中选择名称,其中product_id = 1), (从产品中选择价格,其中product_id = 2));

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

寄离 2024-11-24 15:59:54
INSERT INTO Products (name, price)
VALUES 
((SELECT name, price 
    FROM Products  
   WHERE product_id = 1));
INSERT INTO Products (name, price)
VALUES 
((SELECT name, price 
    FROM Products  
   WHERE product_id = 1));
乖乖公主 2024-11-24 15:59:54

如果您想使用单个 SQL 语句克隆一行,并且不能或不想列出所有值,但有一个主键,您可以使用:

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);

这会尝试将该行的两个副本插入数据库,并且当第一行插入由于重复的product_id而失败,它使用ON DUPLICATE KEY将表中的现有行更新为下一个可用的product_id,这使得原始product_id在插入第二行时可用。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文