gpt4 book ai didi

sql - 在 PostgreSQL 中提供版本化行的好方法是什么?如何查询?

转载 作者:行者123 更新时间:2023-11-29 11:33:54 25 4
gpt4 key购买 nike

我想在一个表中存储不同版本的不同文本和其他数据。对于文本,我的表格如下所示:

id BigSerial, PRIMARY KEY  
version Integer
text Text
origin BigInt

现在我想像这样在这个表中存储不同版本的文本:

1,0,"My Text, first Version",null  
2,1,"My Text, second Version",1
3,0,"My 2nd Text v1",null
4,1,"My 2nd Text v2",3

我还不知道如何为每组文本查询版本号最高的行。

最佳答案

Bigserial id 号没有任何用处。

create temp table my_table (
id integer not null,
version integer not null check(version > 0),
-- Give a lot of thought to whether text should also be unique. *I* think
-- it probably should, but it's really application-dependent.
text Text not null unique,
primary key (id, version)
);

insert into my_table values
(1, 1, 'My Text, first Version'),
(1, 2, 'My Text, second Version'),
(2, 1, 'My 2nd text v1'),
(2, 2, 'My 2nd text v2')

每个 id 的版本数。

select id, count(*)
from my_table
group by id;

每个 id 的当前版本。

with current_ver as (
select id, max(version) as version
from my_table
group by id
)
select m.* from my_table m
inner join current_ver c on c.id = m.id and c.version = m.version

虽然我是用一个公用表表达式写的,但您可能想要创建一个当前版本的 View 。我认为大多数访问此数据的应用程序都需要当前版本。

关于sql - 在 PostgreSQL 中提供版本化行的好方法是什么?如何查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9254189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com