Copy row but with new id

后端 未结 6 1033
有刺的猬
有刺的猬 2020-12-07 22:36

I have a table \"test\" with an auto incremented id and an arbitrary number of columns.

I want to make a copy of a row in this table with all columns th

6条回答
  •  情书的邮戳
    2020-12-07 23:15

    Let us say your table has following fields:

    ( pk_id int not null auto_increment primary key,
      col1 int,
      col2 varchar(10)
    )
    

    then, to copy values from one row to the other row with new key value, following query may help

    insert into my_table( col1, col2 ) select col1, col2 from my_table where pk_id=?;
    

    This will generate a new value for pk_id field and copy values from col1, and col2 of the selected row.

    You can extend this sample to apply for more fields in the table.

    UPDATE:
    In due respect to the comments from JohnP and Martin -

    We can use temporary table to buffer first from main table and use it to copy to main table again. Mere update of pk reference field in temp table will not help as it might already be present in the main table. Instead we can drop the pk field from the temp table and copy all other to the main table.

    With reference to the answer by Tim Ruehsen in the referred posting:

    CREATE TEMPORARY TABLE tmp SELECT * from my_table WHERE ...;
    ALTER TABLE tmp drop pk_id; # drop autoincrement field
    # UPDATE tmp SET ...; # just needed to change other unique keys
    INSERT INTO my_table SELECT 0,tmp.* FROM tmp;
    DROP TEMPORARY TABLE tmp;
    

    Hope this helps.

提交回复
热议问题