How to copy a row and insert in same table with a autoincrement field in MySQL?

后端 未结 13 1097
旧时难觅i
旧时难觅i 2020-11-29 15:55

In MySQL I am trying to copy a row with an autoincrement column ID=1 and insert the data into same table as a new row with

13条回答
  •  北荒
    北荒 (楼主)
    2020-11-29 16:47

    IMO, the best seems to use sql statements only to copy that row, while at the same time only referencing the columns you must and want to change.

    CREATE TEMPORARY TABLE temp_table ENGINE=MEMORY
    
    SELECT * FROM your_table WHERE id=1;
    UPDATE temp_table SET id=NULL; /* Update other values at will. */
    
    INSERT INTO your_table SELECT * FROM temp_table;
    DROP TABLE temp_table;
    

    See also av8n.com - How to Clone an SQL Record

    Benefits:

    • The SQL statements 2 mention only the fields that need to be changed during the cloning process. They do not know about – or care about – other fields. The other fields just go along for the ride, unchanged. This makes the SQL statements easier to write, easier to read, easier to maintain, and more extensible.
    • Only ordinary MySQL statements are used. No other tools or programming languages are required.
    • A fully-correct record is inserted in your_table in one atomic operation.

提交回复
热议问题