postgreSQL:如何复制行
这是我的table web_书的方案:postgreSQL:如何复制行,postgresql,Postgresql,这是我的table web_书的方案: Column | Type | Modifiers ----------------+------------------------+------------------------------------------------------- id | integer
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
您需要为新插入的行创建新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;
在这种情况下,您不需要知道序列名称(但发生的情况不太明显)。仅在指定其值时指定
id
列(这不是您的情况)。您想使用下一个序列web\u book\u id\u seq
值,所以不要在插入查询中指定它
您的插入应该如下所示:
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;
@clime由于
nextval
是id
列的默认值,因此无需声明它INSERT-INTO-web\u-book(page\u-count,…)选择page\u-count,…
@clime:让默认设置生效不仅更简单,而且还可以避免以后出现其他错误。如果您在序列后面手动添加下一个id
,则序列不会递增。依赖默认值的下一行中的一行可能会从手动INSERT
已复制的序列中提取一个数字。不要这样做,或者在之后让你的序列同步-例如与。