Duplicate / Copy records in the same MySQL table

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

    I just wanted to extend Alex's great answer to make it appropriate if you happen to want to duplicate an entire set of records:

    SET @x=7;
    CREATE TEMPORARY TABLE tmp SELECT * FROM invoices;
    UPDATE tmp SET id=id+@x;
    INSERT INTO invoices SELECT * FROM tmp;
    

    I just had to do this and found Alex's answer a perfect jumping off point!. Of course, you have to set @x to the highest row number in the table (I'm sure you could grab that with a query). This is only useful in this very specific situation, so be careful using it when you don't wish to duplicate all rows. Adjust the math as necessary.

提交回复
热议问题