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

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

    I updated @LeonardChallis's solution as it didn't work for me as none of the others. I removed the WHERE clauses and SET primaryKey = 0 in the temp table so MySQL auto-increments itself the primaryKey

    CREATE TEMPORARY TABLE tmptable SELECT * FROM myTable;
    UPDATE tmptable SET primaryKey = 0;
    INSERT INTO myTable SELECT * FROM tmptable;
    

    This is of course to duplicate all the rows in the table.

    0 讨论(0)
  • 2020-11-27 10:32

    This is an additional solution to the answer by "Grim..." There have been some comments on it having a primary key as null. Some comments about it not working. And some comments on solutions. None of the solutions worked for us. We have MariaDB with the InnoDB table.

    We could not set the primary key to allow null. Using 0 instead of NULL led to duplicate value error for the primary key. SET SQL_SAFE_UPDATES = 0; Did not work either.

    The solution from "Grim..." did work IF we changed our PRIMARY KEY to UNIQUE instead

    0 讨论(0)
提交回复
热议问题