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

后端 未结 26 2372
-上瘾入骨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:06

    This solution showed above works perfect also for selected rows. For example I am creating demonstration rows for my nice2work project, and this works perfect.

    CREATE TEMPORARY TABLE tmptable SELECT * FROM myTable WHERE id=500;
    UPDATE tmptable SET id = 0;
    UPDATE some fields I need to change
    INSERT INTO myTable SELECT * FROM tmptable;
    DROP TABLE tmptable;
    
    //  You can use this same also directly into your code like (PHP Style)
    $sql = "CREATE TEMPORARY TABLE tmptable SELECT * FROM myTable WHERE id=500;
    UPDATE tmptable SET id = 0;
    UPDATE some fields I need to change
    INSERT INTO myTable SELECT * FROM tmptable;DROP TABLE tmptable;";
    

提交回复
热议问题