postgreSQL: how to duplicate a row

前端 未结 2 906
离开以前
离开以前 2020-12-28 12:30

This is the scheme of my table web_book:

     Column     |          Type          |                       Modifiers                       
----------------+-         


        
2条回答
  •  梦谈多话
    2020-12-28 12:50

    You need to create a new ID for the newly inserted row:

    INSERT INTO web_book( 
       id, page_count, year_published, file, image, 
       display_on_hp, name, description, name_cs, 
       name_en, description_cs, description_en
    )
    SELECT nextval('web_book_id_seq'), 
           page_count, 
           year_published, 
           file, 
           image, 
           display_on_hp, 
           name, 
           description, 
           name_cs, 
           name_en, 
           description_cs, 
           description_en 
    FROM web_book WHERE id=3;
    

    As mentioned by ClodoaldoNeto you can make things a bit easier by simply leaving out the ID column and let the default definition do its job:

    INSERT INTO web_book( 
       page_count, year_published, file, image, 
       display_on_hp, name, description, name_cs, 
       name_en, description_cs, description_en
    )
    SELECT page_count, 
           year_published, 
           file, 
           image, 
           display_on_hp, 
           name, 
           description, 
           name_cs, 
           name_en, 
           description_cs, 
           description_en 
    FROM web_book WHERE id=3;
    

    In this case you don't need to know the sequence name (but it is a bit less obvious what's going on).

提交回复
热议问题