如何使用自动生成的id插入Postgres表



我正在尝试将当前行的副本添加到表中,并进行一些更改。

我有一张桌子,例如有3个柱子(id,col1,col2(,和2行(492d0a75,some_text1,some_txt2(。

我的表的列Id不是自动递增的,我使用:

@Id
@GeneratedValue(generator = "uuid_gen")
@GenericGenerator(name = "uuid_gen", strategy = "uuid2")
@Column(name = "id", length = 36)

hibernate注释生成unic id。

我想做这样的事情:

insert into mytable(id, col1, col2)
select id, col1, 'other_value'
from mytable;

但不能这样做,因为id将不是唯一的。

我该怎么做?

要做到这一点,我要安装"uuid ossp">

要安装uuidossp模块,您可以使用CREATEEXTENSION语句,如下所示:

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

之后,现在我可以使用postgres文档中的uuid_generate_v4((

我的最后一个查询是这样的:

insert into mytable (id, col1, col2)
select uuid_generate_v4(), col1, 'other_value'
from mytable;

最新更新