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

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

    I used Leonard Challis's technique with a few changes:

    CREATE TEMPORARY TABLE tmptable_1 SELECT * FROM table WHERE primarykey = 1;
    UPDATE tmptable_1 SET primarykey = NULL;
    INSERT INTO table SELECT * FROM tmptable_1;
    DROP TEMPORARY TABLE IF EXISTS tmptable_1;
    

    As a temp table, there should never be more than one record, so you don't have to worry about the primary key. Setting it to null allows MySQL to choose the value itself, so there's no risk of creating a duplicate.

    If you want to be super-sure you're only getting one row to insert, you could add LIMIT 1 to the end of the INSERT INTO line.

    Note that I also appended the primary key value (1 in this case) to my temporary table name.

提交回复
热议问题