Duplicate / Copy records in the same MySQL table

前端 未结 9 1047
我在风中等你
我在风中等你 2020-12-04 06:27

I have been looking for a while now but I can not find an easy solution for my problem. I would like to duplicate a record in a table, but of course, the unique primary key

9条回答
  •  粉色の甜心
    2020-12-04 06:56

    Slight variation, main difference being to set the primary key field ("varname") to null, which produces a warning but works. By setting the primary key to null, the auto-increment works when inserting the record in the last statement.

    This code also cleans up previous attempts, and can be run more than once without problems:

    DELETE FROM `tbl` WHERE varname="primary key value for new record";
    DROP TABLE tmp;
    CREATE TEMPORARY TABLE tmp SELECT * FROM `tbl` WHERE varname="primary key value for old record";
    UPDATE tmp SET varname=NULL;
    INSERT INTO `tbl` SELECT * FROM tmp;
    

提交回复
热议问题