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

后端 未结 13 999
旧时难觅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:31

    If you're able to use MySQL Workbench, you can do this by right-clicking the row and selecting 'Copy row', and then right-clicking the empty row and selecting 'Paste row', and then changing the ID, and then clicking 'Apply'.

    Copy the row:

    Paste the copied row into the blank row:

    Change the ID:

    Apply:

    0 讨论(0)
  • 2020-11-29 16:33

    This helped and it supports a BLOB/TEXT columns.

    CREATE TEMPORARY TABLE temp_table
    AS
    SELECT * FROM source_table WHERE id=2;
    UPDATE temp_table SET id=NULL WHERE id=2;
    INSERT INTO source_table SELECT * FROM temp_table;
    DROP TEMPORARY TABLE temp_table;
    USE source_table;
    
    0 讨论(0)
  • 2020-11-29 16:35
    insert into MyTable(field1, field2, id_backup)
        select field1, field2, uniqueId from MyTable where uniqueId = @Id;
    
    0 讨论(0)
  • 2020-11-29 16:36

    A lot of great answers here. Below is a sample of the stored procedure that I wrote to accomplish this task for a Web App that I am developing:

    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON
    
    -- Create Temporary Table
    SELECT * INTO #tempTable FROM <YourTable> WHERE Id = Id
    
    --To trigger the auto increment
    UPDATE #tempTable SET Id = NULL 
    
    --Update new data row in #tempTable here!
    
    --Insert duplicate row with modified data back into your table
    INSERT INTO <YourTable> SELECT * FROM #tempTable
    
    -- Drop Temporary Table
    DROP TABLE #tempTable
    
    0 讨论(0)
  • 2020-11-29 16:39

    Say the table is user(id, user_name, user_email).

    You can use this query:

    INSERT INTO user (SELECT NULL,user_name, user_email FROM user WHERE id = 1)
    
    0 讨论(0)
  • 2020-11-29 16:40

    Use INSERT ... SELECT:

    insert into your_table (c1, c2, ...)
    select c1, c2, ...
    from your_table
    where id = 1
    

    where c1, c2, ... are all the columns except id. If you want to explicitly insert with an id of 2 then include that in your INSERT column list and your SELECT:

    insert into your_table (id, c1, c2, ...)
    select 2, c1, c2, ...
    from your_table
    where id = 1
    

    You'll have to take care of a possible duplicate id of 2 in the second case of course.

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