PostgreSQL:如何复制一行

zpf6vheq  于 2022-12-18  发布在  PostgreSQL
关注(0)|答案(3)|浏览(211)

这是我的表web_book的方案:

Column     |          Type          |                       Modifiers                       
----------------+------------------------+-------------------------------------------------------
 id             | integer                | not null default nextval('web_book_id_seq'::regclass)
 page_count     | integer                | not null
 year_published | integer                | not null
 file           | character varying(100) | not null
 image          | character varying(100) | not null
 display_on_hp  | boolean                | not null
 name           | character varying(128) | not null
 description    | text                   | not null
 name_cs        | character varying(128) | 
 name_en        | character varying(128) | 
 description_cs | text                   | 
 description_en | text                   |

该表包含一行id=3。我想复制该行,但如果我尝试:

INSERT INTO web_book SELECT * FROM web_book WHERE id=3;

我得到这个:

ERROR:  duplicate key value violates unique constraint "web_book_pkey"
DETAIL:  Key (id)=(3) already exists

pexxcrt2

pexxcrt21#

您需要为新插入的行创建一个新ID:

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;

正如ClodoaldoNeto所提到的,您可以通过省略ID列并让默认定义完成它的工作来使事情变得简单一些:

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;

在这种情况下,您不需要知道序列名(但这并不明显)。

ijnw1ujt

ijnw1ujt2#

仅当指定了id列的值时才指定该列(并且这不是您的情况)。您希望使用下一个序列web_book_id_seq值,因此不要在INSERT查询中指定它。
您的INSERT应该如下所示:

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;
6ie5vjzr

6ie5vjzr3#

另一种选择。
注意在这个例子中,prtkey和pubkey是bytea类型的二进制字段,uptime是一个timestamptz非空字段。

INSERT INTO keysvc (id,title,pvtkey,pubkey,status,uptime) VALUES( 2, 'ramnode4',null ,null ,1, CURRENT_TIMESTAMP);

with keys as (SELECT pvtkey, pubkey, uptime FROM keysvc where id = 1)
update keysvc set pvtkey=(select pvtkey from keys), pubkey=(select pvtkey from keys), uptime=(select uptime from keys) where id =40;

相关问题