In MySQL, can I copy one row to insert into the same table?

后端 未结 26 2292
-上瘾入骨i
-上瘾入骨i 2020-11-27 09:56
insert into table select * from table where primarykey=1

I just want to copy one row to insert into the same table (i.e., I want to duplicate an ex

26条回答
  •  离开以前
    2020-11-27 10:19

    If your table's primary key field is an auto increment field, then you can use query with columns. For example, your table named test_tbl has 3 fields as id, name, age. id is a primary key field and auto increment, so you can use the following query to duplicate the row:

    INSERT INTO `test_tbl` (`name`,`age`) SELECT `name`,`age` FROM `test_tbl`;
    

    This query results in duplicating every row.


    If your table's primary key field is not an auto increment field, then you can use the following method:

    INSERT INTO `test_tbl` (`id`,`name`,`age`)
      SELECT 20,`name`,`age` FROM `test_tbl` WHERE id = 19;
    

    The result of this query is a duplicate row of id=19 inserted as id=20.

提交回复
热议问题