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

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

    I'm assuming you want the new record to have a new primarykey? If primarykey is AUTO_INCREMENT then just do this:

    INSERT INTO table (col1, col2, col3, ...)
    SELECT col1, col2, col3, ... FROM table
      WHERE primarykey = 1
    

    ...where col1, col2, col3, ... is all of the columns in the table except for primarykey.

    If it's not an AUTO_INCREMENT column and you want to be able to choose the new value for primarykey it's similar:

    INSERT INTO table (primarykey, col2, col3, ...)
    SELECT 567, col2, col3, ... FROM table
      WHERE primarykey = 1
    

    ...where 567 is the new value for primarykey.

提交回复
热议问题