Duplicate / Copy records in the same MySQL table

前端 未结 9 1040
我在风中等你
我在风中等你 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:44

    A late answer I know, but it still a common question, I would like to add another answer that It worked for me, with only using a single line insert into statement, and I think it is straightforward, without creating any new table (since it could be an issue with CREATE TEMPORARY TABLE permissions):

    INSERT INTO invoices (col_1, col_2, col_3, ... etc)
      SELECT
        t.col_1,
        t.col_2,
        t.col_3,
        ...
        t.updated_date,
      FROM invoices t;
    

    The solution is working for AUTO_INCREMENT id column, otherwise, you can add ID column as well to statement:

    INSERT INTO invoices (ID, col_1, col_2, col_3, ... etc)
      SELECT
        MAX(ID)+1,
        t.col_1,
        t.col_2,
        t.col_3,
        ... etc ,
      FROM invoices t;
    

    It is really easy and straightforward, you can update anything else in a single line without any second update statement for later, (ex: update a title column with extra text or replacing a string with another), also you can be specific with what exactly you want to duplicate, if all then it is, if some, you can do so.

提交回复
热议问题